Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect & query MySQL from within Lua?

Tags:

mysql

lua

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

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

like image 449
TeddyH Avatar asked Aug 08 '10 02:08

TeddyH


2 Answers

Minimal woking example for LuaSQL - simple interface from Lua to a 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.

like image 57
Stanislav Ivanov Avatar answered Oct 04 '22 21:10

Stanislav Ivanov


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
like image 24
Judge Maygarden Avatar answered Oct 04 '22 21:10

Judge Maygarden