Lua データベースアクセス

この記事では主に Lua データベースの操作ライブラリを紹介します:LuaSQLこれはオープンソースで、サポートしているデータベースは:ODBC、ADO、Oracle、MySQL、SQLite、PostgreSQL。

この記事では MySQL のデータベース接続を紹介します。

LuaSQL は使用できますLuaRocksインストールには、必要に応じて必要なデータベースドライバをインストールできます。

LuaRocks のインストール方法:

$ wget http://luarocks.org/releases/luarocks-2.2.1.tar.gz
$ tar zxpf luarocks-2.2.1.tar.gz
$ cd luarocks-2.2.1
$ ./configure; sudo make bootstrap
$ sudo luarocks install luasocket
$ lua
Lua 5.3.0 Copyright (C) 1994-2015 Lua.org, PUC-Rio
> require "socket"

Window での LuaRocks のインストール:https://github.com/keplerproject/luarocks/wiki/Installation-instructions-for-Windows

さまざまなデータベースドライバのインストール:

luarocks install luasql-sqlite3
luarocks install luasql-postgres
luarocks install luasql-mysql
luarocks install luasql-sqlite
luarocks install luasql-odbc

ソースコードからインストールする方法もあります。Lua Github ソースコードのアドレス:https://github.com/keplerproject/luasql

Lua で MySQL データベースに接続:

サンプル

require "luasql.mysql"

-- 環境オブジェクトを作成
env = luasql.mysql()

-- データベースに接続
conn = env:connect("データベース名","ユーザー名","パスワード","IPアドレス",ポート)

-- データベースのエンコーディング形式を設定
conn:execute"SET NAMES UTF8"

-- データベース操作を実行
cur = conn:execute("select * from role")

row = cur:fetch({},"a")

-- ファイルオブジェクトの作成
file = io.open("role.txt","w+");

while row do
    var = string.format("%d %s\n", row.id, row.name)

    print(var)

    file:write(var)

    row = cur:fetch(row,"a")
end


file:close()  -- ファイルオブジェクトを閉じる
conn:close()  -- データベース接続を閉じる
env:close()   -- データベース環境を閉じる
その他の拡張