找回密码
 立即注册
查看: 565|回复: 0

SQLite实现增删改查及创建库表

[复制链接]

17

主题

1

回帖

111

积分

管理员

积分
111
发表于 2024-6-15 19:55:20 | 显示全部楼层 |阅读模式
本文演示创建SQLite数据库及查询、删除与更新
local cjson = require("cjson")

local db = require("sqlite").new()

local response = require("fastweb.response")
-- 清空示例
local function sqlite_delete()
    -- 清空数据
    local ppst = db:setsql("DELETE FROM users")
    ppst:update()
end
-- 插入数据
local function sqlite_insert()
    local ppst = db:setsql("INSERT INTO users(username,password)VALUES(?,?)")
    -- 文本
    ppst:set_str(1,"fastweb")
    ppst:set_str(2,"123456")
    ppst:update()
end
-- 更新数据
local function sqlite_update()
    local ppst = db:setsql("UPDATE users SET password = ? WHERE username = ?")
    ppst:set_str(1,"666666")
    ppst:set_str(2,"fastweb")
    ppst:update()
end
-- 查询数据
local function sqlite_select()
    local ppst = db:setsql("SELECT * FROM users WHERE id > 0")
    ppst:set_i32(1,0)
    -- 查询结果
    local result = ppst:query();

    local users = {}
    while result:next() do
        local user = {
            username = result:get("username"),
            password = result:get("password"),
        }
        table.insert(users,user)
    end
    return users;
end


-- 打开

if dbpen("E:/data.db") == false then
        response.send("sqlite open failed,"..db:last_error())
        return
end
-- 创建表
local ppst = db:setsql("CREATE TABLE users(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, username TEXT, password TEXT );")
if ppst ~= nil then
        ppst:update()
end

--sqlite_delete()
sqlite_insert()
sqlite_update()
sqlite_select()
local users =sqlite_select()
response:send(cjson.encode(users))



您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|Fastweb

GMT+8, 2024-10-18 17:16 , Processed in 0.025136 second(s), 18 queries .

Powered by Discuz! X3.5

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表