lua语法中没有try...catch来处理函数中出现的异常,需要使用pcall或者xpcall来进行异常捕获。
捕获数据库异常并重试
local logger = require "log"
local sqlite3 = require "lsqlite3"
local socket = require("socket")
local function checkSql(SRC)
local db = sqlite3.open("test.db")
local sqlTest = ([[SELECT FBILLNO FROM STUDENT where FBILLNO = '%s']]):format(SRC)
logger.debug("测试数据库连接", sqlTest)
local FBILLNO = "";
for row in db:nrows(sqlTest) do
FBILLNO = row["FBILLNO"]
end
-- 为了防止数据还没有插入到数据库
if string.len(FBILLNO) < 1 then error("not found") end;
print(FBILLNO, "FBILLNO")
logger.debug("数据库连接测试完成")
end
local count = 5
while (count > 0) do
local f, res = pcall(checkSql, "123456")
if f then
count =0
else
-- lua没有sleep函数, 使用socket等待指定时间。
socket.select(nil, nil, 0.5)
count = count - 0.5
logger.debug("数据库连接存在错误,需要重试")
print("failed to call sum function:" .. res)
end
end