新冠疫情能否打开MySQL数据库?

只想知道,是否可以在 Corona 中使用 MySQL 或者使用 sqlite3 打开 MySQL 数据库,或者使用 MySQL 数据库和 sqlite3 数据库有什么区别?

点赞
用户1190388
用户1190388

使用SQLite连接数据库

在Corona中,可以使用自带的SQLite库连接数据库,文档可在这里访问。

local sqlite3 = require "sqlite3"

--打开data.db文件,如果不存在将被创建
local path = system.pathForFile("data.db", system.DocumentsDirectory)
db = sqlite3.open( path )

--监听applicationExit事件,关闭数据库
local function onSystemEvent( event )
    if( event.type == "applicationExit" ) then
        db:close()
    end
end

--设置数据表,若数据表不存在则创建
local tablesetup = [[CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, content, content2);]]
print(tablesetup)
db:exec( tablesetup )

--添加自动编号的行。无需指定值,因为我们将填充它们全部
local testvalue = {}
testvalue[1] = 'Hello'
testvalue[2] = 'World'
testvalue[3] = 'Lua'
local tablefill =[[INSERT INTO test VALUES (NULL, ']]..testvalue[1]..[[',']]..testvalue[2]..[['); ]]
local tablefill2 =[[INSERT INTO test VALUES (NULL, ']]..testvalue[2]..[[',']]..testvalue[1]..[['); ]]
local tablefill3 =[[INSERT INTO test VALUES (NULL, ']]..testvalue[1]..[[',']]..testvalue[3]..[['); ]]
db:exec( tablefill )
db:exec( tablefill2 )
db:exec( tablefill3 )

--打印SQLite版本到终端
print( "version " .. sqlite3.version() )

--打印所有表中的内容
for row in db:nrows("SELECT * FROM test") do
    local text = row.content.." "..row.content2
    local t = display.newText(text, 20, 30 * row.id, null, 16)
    t:setFillColor( 1, 0, 1 )
end

--监听system事件,以捕捉applicationExit
Runtime:addEventListener( "system", onSystemEvent )

除了使用自带的库外,还可以使用第三方库(或“电池”)来创建连接。其中一种广泛使用的库是LuaSQL

在Corona社区的一个帖子中,介绍了如何使用LuaSQL连接MySQL服务器。具体内容请查看这里

local luasql = require "luasql.mysql";
env = assert((luasql.mysql()), "Uh oh, couldn't load driver")
conn = assert(env:connect("database","username","password","localhost"), "Oops!!")
cur = assert (conn:execute ("SELECT * from table_1" ))
row = cur:fetch ({}, "a")
while row do
  print ("\n------ new row ---------\n")
  table.foreach (row, print)
  row = cur:fetch (row, "a")
end
cur:close()
conn:close()
env:close()
2014-03-31 09:54:52