如何连接&从Lua内部查询MySQL?

时间:2010-08-08 02:38:52

标签: mysql lua

如何使用Lua编程语言连接到MySQL数据库?

如果存在好的/受欢迎的图书馆,它是什么?

3 个答案:

答案 0 :(得分:6)

LuaSQL的最小woking示例 - 从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

如果找不到模块luasql.mysql,则使用第1行。也可以使用环境变量LUA_CPATH。

答案 1 :(得分:4)

来自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

答案 2 :(得分:3)

如果您的mysql数据库是远程的,您可以添加host作为另一个可选参数来连接。端口也可以跟随主机:

con = assert (env:connect("dbname","user","password","host",port))