local sqlite3_util = {}
local env = sqlite3.sqlite3()
local toutf8 = iconv.new("UTF-8", "GBK")
local togbk = iconv.new("GBK", "UTF-8")
function sqlite3_util.gbk2utf8(str)
local s, err = toutf8:iconv(str)
if err then
sqlite3_util.send_error_to_tj_user(actor, err)
return str
end
return s
end
function sqlite3_util.utf82gbk(str)
local s, err = togbk:iconv(str)
if err then
sqlite3_util.send_error_to_tj_user(actor, err)
return str
end
return s
end
-- 打开数据库连接
function sqlite3_util.open(db_name)
return env:connect(db_name)
end
-- 关闭数据库连接
function sqlite3_util.close()
return env:close()
end
-- 错误处理函数,只对tj_user类型用户发送错误信息
function sqlite3_util.send_error_to_tj_user(actor, err)
if tj_user[getconst(actor, "<$USERCOUNT>")] then
sendmsg6(actor, err)
end
end
function sqlite3_util.insert(actor, db, table_name, data) -- 传入k,v insert 数据
local columns = {}
local values = {}
-- 构建列名和值列表,注意:这里直接在SQL中插入值,增加了SQL注入风险
local sql_values = {}
for k, v in pairs(data) do
table.insert(columns, k)
table.insert(values, v)
-- 这里应当对v进行适当的转义,以避免SQL注入
sql_values[#sql_values + 1] = "'" .. db:escape(v) .. "'"
end
-- 构建插入的SQL语句,直接使用值列表
local sql_insert = string.format(
"INSERT INTO %s (%s) VALUES (%s)",
table_name,
table.concat(columns, ', '),
table.concat(sql_values, ', ')
)
sql_insert = sqlite3_util.gbk2utf8(sql_insert)
-- 执行SQL语句
local res, err = db:execute(sql_insert)
if err then
sendmsg6(actor, tostring(err))
sqlite3_util.send_error_to_tj_user(actor, err)
return nil, err
end
return res, nil
end
-- 查询数据
function sqlite3_util.select(actor, db, table_name, columns, where_clause)
local select_sql = string.format("SELECT %s FROM %s %s",
columns or '*',
table_name,
where_clause or '')
select_sql = sqlite3_util.gbk2utf8(select_sql)
local res, err = db:execute(select_sql)
if err then
sqlite3_util.send_error_to_tj_user(actor, err)
return nil, err
end
local results = {}
local row
while true do
local row = {res:fetch()}
if #row == 0 then break end
for k, v in ipairs(row) do
row[k] = sqlite3_util.utf82gbk(v)
end
table.insert(results, row)
end
return results, nil
end
-- 更新数据
function sqlite3_util.update(actor, db, table_name, data, where_clause)
local set_clause = ''
-- 构建 SET 子句
for k, v in pairs(data) do
set_clause = set_clause .. k .. ' = "' .. v .. '", '
end
set_clause = set_clause:sub(1, -3) -- 去除最后一个逗号和空格
-- 构建完整的 SQL 语句
local sql_update = string.format("UPDATE %s SET %s %s",
table_name,
set_clause,
where_clause or '')
-- 执行SQL语句
sql_update = sqlite3_util.gbk2utf8(sql_update)
local res, err = db:execute(sql_update)
if err then
sqlite3_util.send_error_to_tj_user(actor, err)
return nil, err
end
return res, nil
end
-- 删除数据
function sqlite3_util.delete(actor, db, table_name, where_clause)
local sql = string.format("DELETE FROM %s %s",
table_name,
where_clause or '')
sql = sqlite3_util.gbk2utf8(sql)
local res, err = db:execute(sql)
if err then
sqlite3_util.send_error_to_tj_user(actor, err)
return nil, err
end
return res, nil
end
return sqlite3_util