18 Lua 与 Mysql

undefined18 Lua 与MYSQL

undefined

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

LuaSQLhttp://luaforge.net/projects/luasql/

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

LuaSQL 可以使用

LuaRockshttps://luarocks.org/

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

undefinedLuaRocks 安装方法:

  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"

undefined通过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)

Id:1 Name:ace Id:2 Name:shit Id:3 Name:gailun Id:4 Name:ben Id:5 Name:akali Id:6 Name:marong Id:7 Name:123 Id:9 Name:songjj Id:10 Name:a Id:12 Name:guanyuhan Id:14 Name:tt-y Id:16 Name:1234 Id:17 Name:1111 Id:18 Name:mike Id:19 Name:pipixia Id:21 Name:qqq Id:22 Name:123123 Id:23 Name:1110 Id:25 Name:he