企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 18 Lua 与MYSQL # 本文主要为大家介绍 Lua 数据库的操作库: [LuaSQL](http://luaforge.net/projects/luasql/) [http://luaforge.net/projects/luasql/](http://luaforge.net/projects/luasql/) 他是开源的,支持的数据库有:ODBC, ADO, Oracle, MySQL, SQLite 和 PostgreSQL。 LuaSQL 可以使用 [LuaRocks](https://luarocks.org/) [https://luarocks.org/](https://luarocks.org/) 来安装可以根据需要安装你需要的数据库驱动。 ## LuaRocks 安装方法: ```lua $ wget https://luarocks.org/releases/luarocks-2.4.1.tar.gz $ tar zxpf luarocks-2.4.1.tar.gz $ cd luarocks-2.4.1 $ ./configure; sudo make bootstrap $ sudo luarocks install luasocket $ lua Lua 5.3.3 Copyright (C) 1994-2016 Lua.org, PUC-Rio > require "socket" ``` ### 通过LuaRocks安装mysql必要的驱动: ```lua sudo luarocks install luasql-mysql MYSQL_INCDIR=/usr/include/mysql/ ``` ```lua mysql = require "luasql.mysql" --创建环境对象 local env = mysql.mysql() --链接数据库 local conn = env:connect("dstorage", "root", "itcast") print(env, conn) print("----------") --执行sql语句 cursor,errorString = conn:execute([[ select * from user]]) --遍历查询结果 row = cursor:fetch({}, "a") while row do print(string.format("Id:%s Name:%s", row.u_id, row.u_name)) row = cursor:fetch({}, "a") end --关闭链接句柄 conn:close() env:close() ``` 执行结果: ```lua 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 ```