Lua - 数据库访问

对于简单的数据操作,我们可能会使用文件,但有时,这些文件操作可能效率不高,可扩展且功能强大.为此,我们可能经常切换到使用数据库. LuaSQL是一个从Lua到许多数据库管理系统的简单接口. LuaSQL是一个库,它为不同类型的SQL提供支持.这包括,

  • SQLite

  • Mysql

  • ODBC

在本教程中,我们将在Lua中介绍MySQL和SQLite的数据库处理.这为两者使用通用接口,并且应该可以将此实现移植到其他类型的数据库.首先让我们看看如何在MySQL中进行操作.

MySQL数据库设置

为了使用以下示例按预期工作,我们需要初始数据库设置.下面列出了这些假设.

  • 您已安装并设置MySQL,默认用户为root,密码为"123456".

  • 您已经创建了数据库测试.

  • 您已经通过MySQL教程了解 MySQL基础知识.

导入MySQL

我们可以使用简单的 require 语句来导入sqlite库,假设您的Lua实现已正确完成.

mysql = require "luasql.mysql"


变量mysql将提供对函数的访问,参考主要的mysql表.

设置连接

我们可以通过启动MySQL环境然后为环境创建连接来建立连接.它显示如下.

local env  = mysql.mysql()
local conn = env:connect('test','root','123456')


上述连接将连接到现有的MySQL文件,并与新创建的文件建立连接.

执行函数

连接有一个简单的执行函数可以帮助我们从创建,插入,删除,更新等操作中完成所有数据库操作.语法如下所示 :

conn:execute([[ 'MySQLSTATEMENT' ]])


在上面的语法中,我们需要确保conn是开放的并且是现有的MySQL连接,并用正确的语句替换'MySQLSTATEMENT'.

创建表示例

下面显示了一个简单的创建表示例.它创建一个表,其中两个参数id为integer类型,名称类型为varchar.

mysql = require "luasql.mysql"

local env  = mysql.mysql()
local conn = env:connect('test','root','123456')

print(env,conn)

status,errorString = conn:execute([[CREATE TABLE sample2 (id INTEGER, name TEXT);]])
print(status,errorString )


运行上述程序时,将创建一个名为sample的表,其中包含两列,即id和name.

MySQL environment (004BB178)	MySQL connection (004BE3C8)
0	nil


如果有任何错误,您将收到错误声明而不是零.一个简单的错误声明如下所示.

LuaSQL: Error executing query. MySQL: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"id INTEGER, name TEXT)' at line 1


插入语句示例

MySQL的插入语句如下所示.

conn:execute([[INSERT INTO sample values('11','Raj')]])


更新语句示例

MySQL的更新语句如下所示.

conn:execute([[UPDATE sample3 SET name='John' where id ='12']])


删除语句示例

MySQL的删除语句如下所示.

conn:execute([[DELETE from sample3 where id ='12']])


选择语句示例

就select语句而言,我们需要循环遍历每一行并提取所需的数据.一个简单的select语句如下所示.

cursor,errorString = conn:execute([[select * from sample]])
row = cursor:fetch ({}, "a")

while row do
   print(string.format("Id: %s, Name: %s", row.id, row.name))
   -- reusing the table of results
   row = cursor:fetch (row, "a")
end


在在上面的代码中,conn是一个开放的MySQL连接.在execute语句返回的游标的帮助下,您可以遍历表响应并获取所需的选择数据.

完整示例

下面给出了包括以上所有陈述的完整示例.

mysql = require "luasql.mysql"

local env  = mysql.mysql()
local conn = env:connect('test','root','123456')
print(env,conn)

status,errorString = conn:execute([[CREATE TABLE sample3 (id INTEGER, name TEXT)]])
print(status,errorString )

status,errorString = conn:execute([[INSERT INTO sample3 values('12','Raj')]])
print(status,errorString )

cursor,errorString = conn:execute([[select * from sample3]])
print(cursor,errorString)

row = cursor:fetch ({}, "a")

while row do
   print(string.format("Id: %s, Name: %s", row.id, row.name))
   row = cursor:fetch (row, "a")
end

-- close everything
cursor:close()
conn:close()
env:close()


当你运行上面的程序时,你将得到以下输出.

MySQL environment (0037B178)	MySQL connection (0037EBA8)
0	nil
1	nil
MySQL cursor (003778A8)	nil
Id: 12, Name: Raj


执行事务

事务是一种确保数据一致性的机制.交易应具有以下四个属性 :

  • 原子性 : 交易完成或根本没有任何事情发生.

  • 一致性 : 交易必须以一致的状态开始,并使系统保持一致状态.

  • 隔离 : 在当前交易之外,交易的中间结果不可见.

  • 耐久性 : 提交事务后,即使系统出现故障,效果也会持续存在.

事务以START TRANSACTION开始;并以commit或rollback语句结束.

启动事务

为了启动事务,我们需要在Lua中执行以下语句,假设conn是一个开放的MySQL连接.

conn:execute([[START TRANSACTION;]])


回滚事务

我们需要执行以下语句来回滚执行启动事务后所做的更改.

conn:execute([[ROLLBACK;]])


提交交易

我们需要执行以下语句来提交执行启动事务后所做的更改.

conn:execute([[COMMIT;]])


我们在上面和后面的章节中已经了解了MySQL的基本SQL操作.记住事务,虽然没有再针对SQLite3进行解释,但同样的语句也适用于SQLite3.

导入SQLite

我们可以使用简单的要求假设您的Lua实现正确完成,导入SQLite库的语句.在安装过程中,包含数据库相关文件的文件夹libsql.

sqlite3 = require "luasql.sqlite3"


变量sqlite3将通过引用主sqlite3表来提供对函数的访问.

设置连接

我们可以通过启动SQLite环境然后为环境创建连接来设置连接.它显示如下.

local env  = sqlite3.sqlite3()
local conn = env:connect('mydb.sqlite')


上述连接将连接到现有的SQLite文件或创建新的SQLite文件,并与新创建的文件建立连接.

执行函数

连接有一个简单的执行函数可以帮助我们从创建,插入,删除,更新等操作中完成所有数据库操作.语法如下所示 :

conn:execute([[ 'SQLite3STATEMENT' ]])


在上面的语法中,我们需要确保conn是开放的并且是现有的sqlite3连接,并用正确的语句替换'SQLite3STATEMENT'.

创建表示例

下面显示了一个简单的创建表示例.它创建一个表,其中两个参数id为integer类型,名称类型为varchar.

sqlite3 = require "luasql.sqlite3"

local env  = sqlite3.sqlite3()
local conn = env:connect('mydb.sqlite')
print(env,conn)

status,errorString = conn:execute([[CREATE TABLE sample ('id' INTEGER, 'name' TEXT)]])
print(status,errorString )


运行上面的程序时,将创建一个名为sample的表,其中包含两列,即id和name.

SQLite3 environment (003EC918)	SQLite3 connection (00421F08)
0	nil


如果出现错误,将返回错误语句而不是nil.一个简单的错误陈述如下所示.

LuaSQL: unrecognized token: ""'id' INTEGER, 'name' TEXT)"


插入语句示例

SQLite的插入语句如下所示.

conn:execute([[INSERT INTO sample values('11','Raj')]])


选择语句示例

就select语句而言,我们需要循环遍历每一行并提取所需的数据.一个简单的select语句如下所示.

cursor,errorString = conn:execute([[select * from sample]])
row = cursor:fetch ({}, "a")

while row do
   print(string.format("Id: %s, Name: %s", row.id, row.name))
   -- reusing the table of results
   row = cursor:fetch (row, "a")
end


在上面的代码中,conn是一个开放的sqlite3连接.用hel执行语句返回的游标的p,您可以遍历表响应并获取所需的选择数据.

完整示例

A完整的例子包括以上所有陈述.

sqlite3 = require "luasql.sqlite3"

local env  = sqlite3.sqlite3()
local conn = env:connect('mydb.sqlite')
print(env,conn)

status,errorString = conn:execute([[CREATE TABLE sample ('id' INTEGER, 'name' TEXT)]])
print(status,errorString )

status,errorString = conn:execute([[INSERT INTO sample values('1','Raj')]])
print(status,errorString )

cursor,errorString = conn:execute([[select * from sample]])
print(cursor,errorString)

row = cursor:fetch ({}, "a")

while row do
   print(string.format("Id: %s, Name: %s", row.id, row.name))
   row = cursor:fetch (row, "a")
end

-- close everything
cursor:close()
conn:close()
env:close()


当你运行时在上面的程序中,你将获得以下输出.

SQLite3 environment (005EC918)	SQLite3 connection (005E77B0)
0	nil
1	nil
SQLite3 cursor (005E9200)	nil
Id: 1, Name: Raj


我们可以执行所有可用的查询在这个libsql库的帮助下.所以,请不要停止这些例子.在Lua中试验各自的MySQL,SQLite3和其他受支持的数据库中提供的各种查询语句.