LuaスクリプトからMySQLを利用するサンプル

LuaスクリプトからMySQLにDB作成・INSERT・SELECTを行うサンプル。 ※CentOSの場合、EPELのluaとlua-sql-mysqlパッケージを入れておくこと。 [lua] require "luasql.mysql" require "socket" function rows (connection, sql_statement) local cursor = assert (connection:execute (sql_statement)) return function () return cursor:fetch() end end env = assert(luasql.mysql()) con = assert(env:connect("DB名", "ユーザーID", "パスワード", localhost, 3306)) res = con:execute([[ DROP TABLE logging ]]) res = assert(con:execute([[ CREATE TABLE logging ( name varchar(50), value varchar(50) ) ]])) — レコード作成 x = socket.gettime() list = {} for i=1,100000 do table.insert(list, { name="Test1", value="Test1 Value", }); end print(string.format("Initialize elapsed time: %.6f\n", socket.gettime() – x)) — レコードをDBにINSERT for i,p in pairs (list) do res = assert (con:execute(string.format([[ INSERT INTO logging VALUES (‘%s’, ‘%s’)]], p.name, p.value) )) end print(string.format("Insert elapsed time: %.6f\n", socket.gettime() – x)) — DBからレコード取得(イテレータ未使用版) cur = assert(con:execute([[ SELECT name, value from logging ]])) print(string.format("Execute elapsed time: %.6f\n", socket.gettime() – x)) print("Num is ".. cur:numrows()); row = cur:fetch({}, "a") while row do — print(string.format("Name: %s, Value: %s", row.name, row.value)) row = cur:fetch(row, "a") end print(string.format("Fetch elapsed time: %.6f\n", socket.gettime() – x)) cur:close() — DBからレコード取得(イテレータ使用版) for name, value in rows (con, [[ SELECT name, value from logging ]]) do — print(string.format("Name: %s, Value: %s", name, value)) end print(string.format("Fetch/Execute elapsed time: %.6f\n", socket.gettime() – x)) cur:close() con:close() env:close() [/lua]
カテゴリー: Lua パーマリンク

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)