Lua两种方式操作MySQL

本文演示FastWeb网站开发中两种方式处理MySQL请求与数据

示例演示如何连接、查询、删除与更新,SQL在文章底部。

原生预处理方式

  • 优点:高度自定义,方便处理复杂逻辑与数据
  • 缺点:不如语句构建器方案简单
Lua 复制代码
local dkjson = require("dkjson")
local conn = mysql_conn.new()

-- 建立连接
function mysql_connect()
    local conn_result = conn:connect("127.0.0.1","root","root","test","utf8mb4",3306)
    if conn_result == 0 then
        -- 连接成功
        return true
    elseif conn_result == 1 then
        -- 连接超时
        return false,"timeout"
    elseif conn_result == 2 then
        -- 连接错误
        return false,conn:last_error()
    end
end
-- 清空示例
function mysql_delete()
    -- 清空数据
    local ppst = conn:setsql("DELETE FROM users")
    ppst:update()
end
-- 插入数据
function mysql_insert()
    local ppst = conn:setsql("INSERT INTO users(username,password,age,data,head)VALUES(?,?,?,?,?)")
    -- 文本
    ppst:set_str(1,"fastweb")
    ppst:set_str(2,"123456")
    -- 数字
    ppst:set_i32(3,25)
    -- 二进制
    ppst:set_str(4,"996\x0088")
    -- 字节流
    local head_file = io.open(website_dir().."/head.png", "rb")
    local head_content = head_file:read("all")
    head_file:close()
    ppst:set_blob(5,head_content)

    ppst:update()
end
-- 更新数据
function mysql_update()
    local ppst = conn:setsql("UPDATE users SET age = ? WHERE username = ?")
    ppst:set_i32(1,66)
    ppst:set_str(2,"fastweb")
    ppst:update()
end
-- 查询数据
function mysql_select()
    local ppst = conn:setsql("SELECT * FROM users WHERE age > ?")
    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"),
            age = result:get("age"),
            data_size = #result:get("data"),
            head_size = #result:get("head")
        }
        table.insert(users,user)
    end
    return users;
end


-- 连接
local is_success,error_msg = mysql_connect()
if is_success == false then
    response:send("connect failed,"..error_msg)
    return
end

mysql_delete();
mysql_insert();
mysql_select();
local users = mysql_select()
response:send(dkjson.encode(users))

SQL构建器方式

  • 优点:集成度高、美观、代码简洁
  • 缺点:不适用较复杂的SQL语句
Lua 复制代码
local dkjson = require("dkjson")
local conn = mysql_conn.new()

-- 建立连接
function mysql_connect()
    local conn_result = conn:connect("127.0.0.1","root","root","test","utf8mb4",3306)
    if conn_result == 0 then
        -- 连接成功
        return true
    elseif conn_result == 1 then
        -- 连接超时
        return false,"timeout"
    elseif conn_result == 2 then
        -- 连接错误
        return false,conn:last_error()
    end
end
-- 清空示例
function mysql_delete()
    -- 清空数据
    conn:delete():table("users"):exec()
end
-- 插入数据
function mysql_insert()
    -- 字节流
    local head_file = io.open(website_dir().."/head.png", "rb")
    local head_content = head_file:read("all")
    head_file:close()

    local insert = conn:insert():table("users")
        :set_str("username","fastweb")
        :set_str("password","123456")
        :set_i32("age",25)
        :set_blob("data","996\x0088")
        :set_blob("head",head_content)
        :exec()
end
-- 更新数据
function mysql_update()
    conn:update():table("users"):set_i32("age",66):where_str("username","=","fastweb"):exec()
end
-- 查询数据
function mysql_select()
    return conn:select():table("users"):field({"username","password","age"}):where_i32("age",">",0):query():table()
end

-- 连接
local is_success,error_msg = mysql_connect()
if is_success == false then
    response:send("connect failed,"..error_msg)
    return
end

mysql_delete();
mysql_insert();
mysql_select();
local users = mysql_select()
response:send(dkjson.encode(users))

SQL文件

Lua 复制代码
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `age` int(11) NULL DEFAULT NULL,
  `data` binary(255) NULL DEFAULT NULL,
  `head` blob NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 38 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;
相关推荐
一叶飘零_sweeeet20 分钟前
从 0 到 1 攻克订单表分表分库:亿级流量下的数据库架构实战指南
java·数据库·mysql·数据库架构·分库分表
苹果醋323 分钟前
数据库索引设计:在 MongoDB 中创建高效索引的策略
java·运维·spring boot·mysql·nginx
TeleostNaCl32 分钟前
如何安装 Google 通用的驱动以便使用 ADB 和 Fastboot 调试(Bootloader)设备
android·经验分享·adb·android studio·android-studio·android runtime
fatiaozhang95271 小时前
中国移动浪潮云电脑CD1000-系统全分区备份包-可瑞芯微工具刷机-可救砖
android·网络·电脑·电视盒子·刷机固件·机顶盒刷机
ホロHoro2 小时前
学习笔记:MYSQL(4)
笔记·学习·mysql
2501_915918412 小时前
iOS 开发全流程实战 基于 uni-app 的 iOS 应用开发、打包、测试与上架流程详解
android·ios·小程序·https·uni-app·iphone·webview
计算机学长felix2 小时前
基于Django的“酒店推荐系统”设计与开发(源码+数据库+文档+PPT)
数据库·python·mysql·django·vue
lichong9512 小时前
【混合开发】vue+Android、iPhone、鸿蒙、win、macOS、Linux之dist打包发布在Android工程asserts里
android·vue.js·iphone
Android出海2 小时前
Android 15重磅升级:16KB内存页机制详解与适配指南
android·人工智能·新媒体运营·产品运营·内容运营
一只修仙的猿2 小时前
毕业三年后,我离职了
android·面试