如何从 Lua 中连接和查询 MySQL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3432864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to connect & query MySQL from within Lua?
提问by TeddyH
How can I connect to a MySQL database from using Lua programming language?
如何使用 Lua 编程语言连接到 MySQL 数据库?
If a good/popular library exists, what is it?
如果存在一个好的/流行的图书馆,它是什么?
回答by Stanislav Ivanov
Minimal woking example for LuaSQL- simple interface from Lua to a DBMS.
LuaSQL 的最小工作示例- 从 Lua 到 DBMS 的简单接口。
package.cpath = package.cpath .. ";/usr/lib/i386-linux-gnu/lua/5.1/?.so"
luasql = require "luasql.mysql"
env = assert (luasql.mysql())
con = assert (env:connect("dbname","user","password"))
cur = assert (con:execute("SHOW TABLES"))
row = cur:fetch ({}, "a")
while row do
print(string.format("Name: %s", row.Tables_in_dbname))
row = cur:fetch (row, "a")
end
Line 1 used if module luasql.mysql not found. Also environment variable LUA_CPATH may be used.
如果未找到模块 luasql.mysql,则使用第 1 行。还可以使用环境变量 LUA_CPATH。
回答by Judge Maygarden
From LuaSQL -- Database connectivity for the Lua programming language:
require "luasql.mysql"
env = assert (luasql.mysql())
con = assert (env:connect"my_db")
for id, name, address in rows (con, "select * from contacts") do
print (string.format ("%s: %s", name, address))
end
回答by NULL pointer
In case your mysql database is remote, you can add host as another optional parameter to connect. Port can follow host as well:
如果你的 mysql 数据库是远程的,你可以添加 host 作为另一个可选参数来连接。端口也可以跟随主机:
con = assert (env:connect("dbname","user","password","host",port))