跳转到内容

$mysql - MySQL 数据库操作

更新: 2026/3/2 字数: 0 字 时长: 0 分钟

$mysql 模块用于在脚本中操作 MySQL 数据库,支持远程数据库连接、表结构管理、增删改查(CRUD)、事务处理、原生 SQL 查询以及数据库状态信息获取等功能,适合用于服务端数据存储与管理。

$mysql.open(options[, callbacks])

  • options {Object}
    数据库连接配置:

    • host {string} MySQL 服务器地址
    • port {number} 端口号,默认 3306
    • user {string} 用户名
    • password {string} 密码
    • database {string} 数据库名称
    • version {number} MySQL 版本号(可选 暂时只支持 MySQL 5.7 )
  • callbacks {Object}(可选)
    生命周期回调:

    • onOpen(db) 数据库连接成功时回调
  • 返回 {Database}

打开 MySQL 数据库连接。

js
let db = $mysql.open({
    host: "127.0.0.1",
    port: 3306,
    user: "root",
    password: "123456",
    database: "test"
}, {
    onOpen: function (db) {
        console.log("数据库已连接");
    }
});

Database

mysql.open 返回的数据库对象。

Database.execSQL(sql[, args])

执行一条不返回结果集的 SQL 语句,常用于建表、删表等操作。

  • sql {string} SQL 语句
  • args {Array | null} SQL 参数
js
db.execSQL("DROP TABLE IF EXISTS STUDENT");
db.execSQL(
    "CREATE TABLE STUDENT (" +
    "id INT AUTO_INCREMENT PRIMARY KEY," +
    "name VARCHAR(20) NOT NULL," +
    "age INT NOT NULL," +
    "score INT" +
    ")"
);

Database.insert(table, values)

  • table {string} 表名
  • values {Object} 键值对形式的数据
  • 返回 {number} 新插入行的 rowId,失败返回 -1

向指定表插入一条记录。

js
var rowId = db.insert("STUDENT", {
    name: "张三",
    age: 18,
    score: 90
});
console.log("新插入的行号:", rowId);

Database.update(table, values, whereClause, whereArgs)

  • table {string} 表名
  • values {Object} 要更新的字段
  • whereClause {string} WHERE 条件(不包含 WHERE)
  • whereArgs {Array} 条件参数
  • 返回 {number} 受影响的行数

更新表中符合条件的记录。

js
var updateCount = db.update(
    "STUDENT",
    { score: 70 },
    "name = ?", 
    ["张三"]
);
console.log("更新的行数:", updateCount);  // 输出:1(如果张三存在)

Database.delete(table, whereClause, whereArgs)

  • table {string} 表名
  • whereClause {string} WHERE 条件
  • whereArgs {Array} 条件参数
  • 返回 {number} 删除的行数

删除表中符合条件的记录。

js
var deleteCount = db.delete("STUDENT", "score > ?", [69]);
console.log("删除的行数:", deleteCount);  // 输出:删了多少条

Database.rawQuery(sql, args)

  • sql {string} SQL 查询语句

  • args {Array | null} SQL 参数

  • 返回 {Cursor} 对象

执行一条原生 SQL 查询语句。

js
var cursor = db.rawQuery("SELECT * FROM STUDENT WHERE age > ?", [17]);

Database.transaction(callback)

  • callback
  • 返回 {Transaction} 对象,可绑定事件监听。

开启一个数据库事务。事务中的所有操作将作为一个整体提交,若抛出异常则回滚。

js
db.transaction(function () {
    db.insert("STUDENT", { name: "事务学生1", age: 22 });
    db.insert("STUDENT", { name: "事务学生2", age: 23 });
});

Database.close()

使用完成后,务必关闭数据库连接以释放资源。

js
db.close();

Database.getVersion()

  • 返回 {number} 数据库版本号

获取数据库版本。

js
console.log("数据库版本:", db.getVersion());

Database.isOpen()

  • 返回 {boolean}

判断数据库是否已打开。

js
console.log("是否打开:", db.isOpen());

Database.inTransaction()

  • 返回 {boolean}

判断当前是否处于事务中。

js
console.log("是否在事务中:", db.inTransaction());

Database.getAutoCommit()

  • 返回 {boolean}

获取当前自动提交状态。

js
console.log("自动提交:", db.getAutoCommit());

Cursor

Cursor 表示一次查询结果集,用于逐行读取数据。


Cursor.moveToNext()

  • 返回 {boolean} 是否还有数据

移动到下一行。


Cursor.pick()

  • 返回 {Object}

获取当前行的所有字段,返回一个对象。

js
while (cursor.moveToNext()) {
  var row = cursor.pick();
  console.log(row);
}
cursor.close();

Cursor.single()

  • 返回 {Object | null}

获取第一条记录。

js
var student = db.rawQuery("SELECT * FROM STUDENT LIMIT 1", []).single();
console.log("第一行:", student);

Cursor.all()

  • 返回 {Array<Object>}

获取所有记录。

js
var list = db.rawQuery("SELECT * FROM STUDENT", []).all();
console.log("全部行:", list);

Transaction 事件

事务对象支持以下事件监听:

begin

事务开始

commit

事务提交成功

rollback

事务回滚

end

事务结束(无论成功或失败)

error

事务执行异常

js
db.transaction(function () {
    db.insert("STUDENT", { name: "事务测试", age: 30 });
}).on("begin", function () {
    console.log("事务开始");
}).on("commit", function () {
    console.log("事务提交");
}).on("rollback", function () {
    console.log("事务回滚");
}).on("end", function () {
    console.log("事务结束");
}).on("error", function (e) {
    console.error(e);
});

示例

查询数据库中的所有表

js


// 完整的 MySQL 测试脚本

// 连接数据库
let db = $mysql.open({
    host: "192.168.0.152",
    port: 3306,
    user: "root",
    password: "123456",
    database: "test",
    version: 5
}, {
    onOpen: function (db) {
        console.log("数据库连接时")

        /*数据库打开时,执行创建数据库表的语句
        我们设计的表名为STUDENT(学生),字段如下:
        id: 整数,自增,键
            name: 学生姓名,文本,非空
            age: 年龄,整数,非空
            score: 分数,整数 */
            // db.execSQL("DROP TABLE IF EXISTS STUDENT");
        // db.execSQL("CREATE TABLE STUDENT (" +
        //     "id INT AUTO_INCREMENT PRIMARY KEY, " +
        //     "name VARCHAR(20) NOT NULL, " +
        //     "age INT NOT NULL, " +
        //     "score INT" +
        //     ")");
    }
});

// ---------- 数据库初始化 ----------
console.log("=== 数据库初始化 ===");
db.execSQL("DROP TABLE IF EXISTS STUDENT");
db.execSQL("CREATE TABLE STUDENT (" +
    "id INT AUTO_INCREMENT PRIMARY KEY, " +
    "name VARCHAR(20) NOT NULL, " +
    "age INT NOT NULL, " +
    "score INT" +
    ")");
console.log("创建表 STUDENT 成功");

// ---------- 插入数据 ----------
console.log("\n=== 插入数据 ===");
console.log("插入张三: ", db.insert("STUDENT", {
    name: "张三",
    age: 18,
    score: 90
}));
console.log("插入李四: ", db.insert("STUDENT", {
    name: "李四",
    age: 19,
    score: 60
}));
console.log("插入王五: ", db.insert("STUDENT", {
    name: "王五",
    age: 20
}));
console.log("插入赵六: ", db.insert("STUDENT", {
    name: "赵六",
    age: 21,
    score: 85
}));

// ---------- 查询数据 ----------
console.log("\n=== 查询数据 ===");

// 查询所有数据
console.log("所有学生数据:");
var allCursor = db.rawQuery("SELECT * FROM STUDENT", []);
console.log(allCursor.all());

// 查询单个数据
console.log("第一个学生数据:");
var singleCursor = db.rawQuery("SELECT * FROM STUDENT LIMIT 1", []);
console.log(singleCursor.single());

// 条件查询
console.log("年龄大于19的学生:");
var ageCursor = db.rawQuery("SELECT * FROM STUDENT WHERE age > ?", [19]);
console.log(ageCursor.all());

// ---------- 修改数据 ----------
console.log("\n=== 修改数据 ===");
console.log("修改李四分数:");
var updateCount = db.update("STUDENT", {
    score: 70
}, "name = ?", ["李四"]);
console.log("影响行数:", updateCount);

console.log("修改后李四的数据:");
var liSiCursor = db.rawQuery("SELECT * FROM STUDENT WHERE name = ?", ["李四"]);
console.log(liSiCursor.single());

// ---------- 删除数据 ----------
console.log("\n=== 删除数据 ===");
console.log("删除分数>80的学生:");
var deleteCount = db.delete("STUDENT", "score > ?", [80]);
console.log("删除行数:", deleteCount);

console.log("删除后的所有数据:");
var afterDeleteCursor = db.rawQuery("SELECT * FROM STUDENT", []);
console.log(afterDeleteCursor.all());

// ---------- 遍历数据 ----------
console.log("\n=== 遍历数据 ===");
console.log("手动遍历学生数据:");
var traverseCursor = db.rawQuery("SELECT * FROM STUDENT ORDER BY age", []);
while (traverseCursor.moveToNext()) {
    var student = traverseCursor.pick();
    console.log(typeof student)
    console.log("学生:", student.name, "年龄:", student.age, "分数:", student.score);
}
traverseCursor.close();




// ---------- 高级查询 ----------
console.log("\n=== 高级查询 ===");

// 分组查询
console.log("按年龄分组统计:");
var groupCursor = db.rawQuery(
    "SELECT age, COUNT(*) as count, AVG(score) as avg_score FROM STUDENT GROUP BY age",
    []
);
console.log(groupCursor.all());

// 排序查询
console.log("按分数降序排列:");
var orderCursor = db.rawQuery(
    "SELECT * FROM STUDENT WHERE score IS NOT NULL ORDER BY score DESC",
    []
);
console.log(orderCursor.all());



// 查询所有表信息
console.log("\n数据库中的所有表:");
var tablesCursor = db.rawQuery(
    "SELECT TABLE_NAME, TABLE_TYPE, ENGINE FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ?",
    ["cloud"]
);
console.log(tablesCursor.all());

// ---------- 批量操作 ----------
console.log("\n=== 批量操作 ===");
var students = [
    { name: "批量1", age: 24, score: 78 },
    { name: "批量2", age: 25, score: 82 },
    { name: "批量3", age: 26, score: 91 }
];

console.log("批量插入学生:");
students.forEach(function (student, index) {
    var id = db.insert("STUDENT", student);
    console.log("插入第" + (index + 1) + "个学生,ID:", id);
});

console.log("批量插入后的数据:");
var batchCursor = db.rawQuery("SELECT * FROM STUDENT ORDER BY id DESC LIMIT 3", []);
console.log(batchCursor.all());

// ---------- 清理测试数据 ----------
console.log("\n=== 清理测试数据 ===");
db.execSQL("DROP TABLE IF EXISTS STUDENT");
console.log("清理完成");

// ---------- 关闭连接 ----------
console.log("\n=== 关闭数据库 ===");
db.close();
console.log("数据库已关闭");

// ---------- 错误处理测试 ----------
console.log("\n=== 错误处理测试 ===");
try {
    // 尝试在关闭后操作数据库
    db.execSQL("SELECT 1");
} catch (e) {
    console.error("预期错误:", e.message);
}

console.log("\n=== 所有测试完成 ===");
// ---------- 关闭远程连接 ----------
db.close();

数据库事务

js
// 连接数据库
let db = $mysql.open({
    host: "192.168.0.152",
    port: 3306,
    user: "root",
    password: "123456",
    database: "test",
    version: 5
}, {
    onOpen: function (db) {
        console.log("数据库打开时")
    }
});
// ---------- 数据库初始化 ----------
console.log("=== 数据库初始化 ===");
db.execSQL("DROP TABLE IF EXISTS STUDENT");
db.execSQL(
  "CREATE TABLE STUDENT (" +
    "id INT AUTO_INCREMENT PRIMARY KEY, " +
    "name VARCHAR(20) NOT NULL, " +
    "age INT NOT NULL, " +
    "score INT" +
    ")"
);
console.log("创建表 STUDENT 成功");

console.log("\n=== 事务测试 ===");
var transactionEmitter = db.transaction(function (tx) {
    console.log("事务中插入数据...");
    db.insert("STUDENT", { name: "事务学生1", age: 22, score: 95 });
    db.insert("STUDENT", { name: "事务学生2", age: 23, score: 88 });
    // 可以取消下面这行的注释来测试回滚
    // throw new Error("测试回滚");
}).on("begin", function (tx) {
    console.log("事务开始");
}).on("commit", function (tx) {
    console.log("事务提交成功");
}).on("rollback", function (tx) {
    console.log("事务回滚");
}).on("end", function (tx) {
    console.log("事务结束");

    // 查看事务后的数据
    console.log("事务后的数据:");
    var afterTxCursor = db.rawQuery("SELECT * FROM STUDENT", []);
    console.log(afterTxCursor.all());
}).on("error", function (e) {
    console.error("事务出错:", e);
});
// ---------- 关闭远程连接 ----------
db.close();

获取数据库信息

js


// 连接数据库
let db = $mysql.open({
    host: "192.168.0.152",
    port: 3306,
    user: "root",
    password: "123456",
    database: "test",
    version: 5
}, {
    onOpen: function (db) {
        console.log("数据库打开时")
    }
});

console.log("数据库版本:", db.getVersion());
console.log("是否在事务中:", db.inTransaction());
console.log("数据库是否打开:", db.isOpen());
console.log("自动提交状态:", db.getAutoCommit());
db.close();