附录2:调用示例
package.cpath = package.cpath .. ';/root/luarocks-3.9.0/lua_modules/lib/lua/5.3/?.so'; --luasql所在目录
local driver = require "luasql.postgres"
env = assert (driver.postgres())
conn = assert (env:connect("postgres","vastbase","Aa@123456","127.0.0.1",5432))
print("connect successful!")
--删除表
conn:execute("drop table tb_test")
--创建表
assert (conn:execute("create table tb_test(id integer not null primary key, name text)"))
print("create table successful!")
--插入数据
assert (conn:execute("insert into tb_test values (1, 'Anna')"))
assert (conn:execute(string.format("insert into tb_test values ('%s', '%s')", 2, 'Jack')))
print("insert successful!")
--查询数据
cur = assert (conn:execute("select * from tb_test"))
row = cur:fetch ({}, "a")
while row do
print(string.format("fetch: id = %s, name: %s", row.id, row.name))
row = cur:fetch (row, "a")
end
--rollback
conn:setautocommit(false)
assert (conn:execute("insert into tb_test values (3, 'Mike')"))
conn:rollback()
conn:commit()
conn:setautocommit(true)
cur = assert (conn:execute("select * from tb_test"))
row = cur:fetch ({}, "a")
while row do
print(string.format("after rollback: id = %s, name: %s", row.id, row.name))
row = cur:fetch (row, "a")
end
--更新数据
conn:execute(string.format("update tb_test set name = '%s' where id = 1",'Elsa'))
print("update successful!")
cur = assert (conn:execute("select * from tb_test"))
row = cur:fetch ({}, "a")
while row do
print(string.format("after update: id = %s, name: %s", row.id, row.name))
row = cur:fetch (row, "a")
end
--删除数据
conn:execute("delete from tb_test where id = 1")
cur = assert (conn:execute("select * from tb_test"))
row = cur:fetch ({}, "a")
while row do
print(string.format("after delete: id = %s, name: %s", row.id, row.name))
row = cur:fetch (row, "a")
end
cur:close()
conn:close()
env:close()