本文主要为大家介绍 Lua 数据库的操作库:

LuaSQL http://luaforge.net/projects/luasql/

他是开源的,支持的数据库有:ODBC, ADO, Oracle, MySQL, SQLite 和 PostgreSQL。

LuaSQL 可以使用

LuaRocks https://luarocks.org/

来安装可以根据需要安装你需要的数据库驱动。

LuaRocks 安装方法:

  1. $ wget https://luarocks.org/releases/luarocks-2.4.1.tar.gz
  2. $ tar zxpf luarocks-2.4.1.tar.gz
  3. $ cd luarocks-2.4.1
  4. $ ./configure; sudo make bootstrap
  5. $ sudo luarocks install luasocket
  6. $ lua
  7. Lua 5.3.3 Copyright (C) 1994-2016 Lua.org, PUC-Rio
  8. > require "socket"

通过LuaRocks安装mysql必要的驱动:

  1. sudo luarocks install luasql-mysql MYSQL_INCDIR=/usr/include/mysql/
  1. mysql = require "luasql.mysql"
  2. --创建环境对象
  3. local env = mysql.mysql()
  4. --链接数据库
  5. local conn = env:connect("dstorage", "root", "itcast")
  6. print(env, conn)
  7. print("----------")
  8. --执行sql语句
  9. cursor,errorString = conn:execute([[ select * from user]])
  10. --遍历查询结果
  11. row = cursor:fetch({}, "a")
  12. while row do
  13. print(string.format("Id:%s Name:%s", row.u_id, row.u_name))
  14. row = cursor:fetch({}, "a")
  15. end
  16. --关闭链接句柄
  17. conn:close()
  18. env:close()

执行结果:

  1. MySQL environment (0x16fb628) MySQL connection (0x16fc108)
  2. ----------
  3. Id:1 Name:ace
  4. Id:2 Name:shit
  5. Id:3 Name:gailun
  6. Id:4 Name:ben
  7. Id:5 Name:akali
  8. Id:6 Name:marong
  9. Id:7 Name:123
  10. Id:9 Name:songjj
  11. Id:10 Name:a
  12. Id:12 Name:guanyuhan
  13. Id:14 Name:tt-y
  14. Id:16 Name:1234
  15. Id:17 Name:1111
  16. Id:18 Name:mike
  17. Id:19 Name:pipixia
  18. Id:21 Name:qqq
  19. Id:22 Name:123123
  20. Id:23 Name:1110
  21. Id:25 Name:he