41_DatabaseDemo.lua 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. -- Database demo. This sample demonstrates how to use database subsystem to connect to a database and execute adhoc SQL statements.
  2. require "LuaScripts/Utilities/Sample"
  3. local connection
  4. local row
  5. local maxRows = 50
  6. function Start()
  7. -- Execute the common startup for samples
  8. SampleStart()
  9. -- Disable default execution of Lua from the console
  10. SetExecuteConsoleCommands(false)
  11. -- Subscribe to console commands and the frame update
  12. SubscribeToEvent("ConsoleCommand", "HandleConsoleCommand")
  13. SubscribeToEvent("Update", "HandleUpdate")
  14. -- Subscribe key down event
  15. SubscribeToEvent("KeyDown", "HandleEscKeyDown")
  16. -- Hide logo to make room for the console
  17. SetLogoVisible(false)
  18. -- Show the console by default, make it large
  19. console.numRows = graphics.height / 16
  20. console.numBufferedRows = 2 * console.numRows
  21. console.commandInterpreter = "LuaScriptEventInvoker"
  22. console.visible = true
  23. console.closeButton.visible = false
  24. -- Show OS mouse cursor
  25. input.mouseVisible = true
  26. -- Open the operating system console window (for stdin / stdout) if not open yet
  27. -- Do not open in fullscreen, as this would cause constant device loss
  28. if not graphics.fullscreen then
  29. OpenConsoleWindow()
  30. end
  31. -- In general, the connection string is really the only thing that need to be changed when switching underlying database API
  32. -- and that when using ODBC API then the connection string must refer to an already installed ODBC driver
  33. -- Although it has not been tested yet but the ODBC API should be able to interface with any vendor provided ODBC drivers
  34. -- In this particular demo, however, when using ODBC API then the SQLite-ODBC driver need to be installed
  35. -- The SQLite-ODBC driver can be built from source downloaded from http:--www.ch-werner.de/sqliteodbc/
  36. -- You can try to install other ODBC driver and modify the connection string below to match your ODBC driver
  37. -- Both DSN and DSN-less connection string should work
  38. -- The ODBC API, i.e. URHO3D_DATABASE_ODBC build option, is only available for native (including RPI) platforms
  39. -- and it is designed for development of game server connecting to ODBC-compliant databases in mind
  40. -- This demo will always work when using SQLite API as the SQLite database engine is embedded inside Urho3D game engine
  41. -- and this is also the case when targeting Web platform
  42. -- We could have used #ifdef to init the connection string during compile time, but below shows how it is done during runtime
  43. -- The "URHO3D_DATABASE_ODBC" compiler define is set when URHO3D_DATABASE_ODBC build option is enabled
  44. -- Connect to a temporary in-memory SQLite database
  45. connection = database:Connect(GetDBAPI() == DBAPI_ODBC and "Driver=SQLite3;Database=:memory:" or "file://")
  46. -- Subscribe to database cursor event to loop through query resultset
  47. SubscribeToEvent("DbCursor", "HandleDbCursor")
  48. -- Show instruction
  49. print([[This demo connects to temporary in-memory database.
  50. All the tables and their data will be lost after exiting the demo.
  51. Enter a valid SQL statement in the console input and press Enter to execute.
  52. Enter 'get/set maxrows [number]' to get/set the maximum rows to be printed out.
  53. Enter 'get/set connstr [string]' to get/set the database connection string and establish a new connection to it.
  54. Enter 'quit' or 'exit' to exit the demo.
  55. For example:]])
  56. HandleInput("create table tbl1(col1 varchar(10), col2 smallint)")
  57. HandleInput("insert into tbl1 values('Hello', 10)")
  58. HandleInput("insert into tbl1 values('World', 20)")
  59. HandleInput("select * from tbl1")
  60. end
  61. function HandleConsoleCommand(eventType, eventData)
  62. if eventData["Id"]:GetString() == "LuaScriptEventInvoker" then
  63. HandleInput(eventData["Command"]:GetString())
  64. end
  65. end
  66. function HandleUpdate(eventType, eventData)
  67. -- Check if there is input from stdin
  68. local input = GetConsoleInput()
  69. if input:len() > 0 then
  70. HandleInput(input)
  71. end
  72. end
  73. function HandleEscKeyDown(eventType, eventData)
  74. -- Unlike the other samples, exiting the engine when ESC is pressed instead of just closing the console
  75. if eventData["Key"]:GetInt() == KEY_ESC then
  76. engine:Exit()
  77. end
  78. end
  79. function HandleDbCursor(eventType, eventData)
  80. -- In a real application the P_SQL can be used to do the logic branching in a shared event handler
  81. -- However, this is not required in this sample demo
  82. local colValues = eventData["ColValues"]:GetVariantVector()
  83. local colHeaders = eventData["ColHeaders"]:GetStringVector()
  84. -- In this sample demo we just use db cursor to dump each row immediately so we can filter out the row to conserve memory
  85. -- In a real application this can be used to perform the client-side filtering logic
  86. eventData["Filter"] = true
  87. -- In this sample demo we abort the further cursor movement when maximum rows being dumped has been reached
  88. row = row + 1
  89. eventData["Abort"] = row >= maxRows
  90. for i, colHeader in ipairs(colHeaders) do
  91. print("Row #" .. row .. ": " .. colHeader .. " = " .. colValues[i])
  92. end
  93. end
  94. function HandleInput(input)
  95. -- Echo input string to stdout
  96. print(input)
  97. row = 0
  98. if input == "quit" or input == "exit" then
  99. engine:Exit()
  100. elseif input:find("set") or input:find("get") then
  101. -- We expect a key/value pair for 'set' command
  102. local command, setting, value
  103. _, _, command, setting, value = input:find("([gs]et)%s*(%a*)%s*(.*)")
  104. if command == "set" and value ~= nil then
  105. if setting == "maxrows" then
  106. maxRows = Max(value, 1)
  107. elseif (setting == "connstr") then
  108. local newConnection = database:Connect(value)
  109. if newConnection ~= nil then
  110. database:Disconnect(connection)
  111. connection = newConnection
  112. end
  113. end
  114. end
  115. if setting ~= nil then
  116. if setting == "maxrows" then
  117. print("maximum rows is set to " .. maxRows)
  118. elseif setting == "connstr" then
  119. print("connection string is set to " .. connection.connectionString)
  120. else
  121. print("Unrecognized setting: " .. setting)
  122. end
  123. else
  124. print("Missing setting paramater. Recognized settings are: maxrows, connstr")
  125. end
  126. else
  127. -- In this sample demo we use the dbCursor event to loop through each row as it is being fetched
  128. -- Regardless of this event is being used or not, all the fetched rows will be made available in the DbResult object,
  129. -- unless the dbCursor event handler has instructed to filter out the fetched row from the final result
  130. local result = connection:Execute(input, true)
  131. -- Number of affected rows is only meaningful for DML statements like insert/update/delete
  132. if result.numAffectedRows ~= -1 then
  133. print("Number of affected rows: " .. result.numAffectedRows)
  134. end
  135. end
  136. print(" ")
  137. end
  138. -- Create XML patch instructions for screen joystick layout specific to this sample app
  139. function GetScreenJoystickPatchString()
  140. return
  141. "<patch>" ..
  142. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button2']]\">" ..
  143. " <attribute name=\"Is Visible\" value=\"false\" />" ..
  144. " </add>" ..
  145. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Hat0']]\">" ..
  146. " <attribute name=\"Is Visible\" value=\"false\" />" ..
  147. " </add>" ..
  148. "</patch>"
  149. end