How to connect & query MySQL from within Lua?

时间:2022-09-18 13:14:07

How can I connect to a MySQL database from using Lua programming language?

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

If a good/popular library exists, what is it?

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

3 个解决方案

#1


5  

Minimal woking example for LuaSQL - simple interface from Lua to a DBMS.

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

Line 1 used if module luasql.mysql not found. Also environment variable LUA_CPATH may be used.

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

#2


4  

From LuaSQL -- Database connectivity for the Lua programming language:

来自LuaSQL - Lua编程语言的数据库连接:

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

#3


3  

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))

#1


5  

Minimal woking example for LuaSQL - simple interface from Lua to a DBMS.

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

Line 1 used if module luasql.mysql not found. Also environment variable LUA_CPATH may be used.

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

#2


4  

From LuaSQL -- Database connectivity for the Lua programming language:

来自LuaSQL - Lua编程语言的数据库连接:

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

#3


3  

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))