electron使用sqlcipher中db.exec和db.run区别及用法与示例
electron使用sqlcipher中db.exec和db.run区别及用法与示例在 SQLCipher 中, `db.exec`和`db.run`是用于执行 SQL 语句的方法。它们的主要区别在于返回值和使用场景。
###`db.exec`
`db.exec`用于执行不返回结果集的 SQL 语句,比如`CREATE` 、 `INSERT` 、 `UPDATE`和`DELETE`等。它会返回一个 Promise,表示执行的结果。
**示例:**
const sqlite3 = require('sqlite3').verbose();
const SQLCipher = require('sqlcipher');
let db = new SQLCipher.Database('test.db');
// 使用密码打开数据库
db.exec("PRAGMA key = 'your_password';", (err) => {
if (err) {
console.error(err.message);
} else {
// 创建表
db.exec("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT);", (err) => {
if (err) {
console.error(err.message);
}
});
}
});
###`db.run`
`db.run`也是用于执行不返回结果集的 SQL 语句,但它允许你绑定参数并且可以获取执行后的行数等信息。它通常用于需要返回执行状态的场景。
**示例:**
const sqlite3 = require('sqlite3').verbose();
const SQLCipher = require('sqlcipher');
let db = new SQLCipher.Database('test.db');
// 使用密码打开数据库
db.exec("PRAGMA key = 'your_password';", (err) => {
if (err) {
console.error(err.message);
} else {
// 插入数据
db.run("INSERT INTO users (name) VALUES (?)", ['Alice'], function(err) {
if (err) {
console.error(err.message);
} else {
console.log(`插入的行 ID: ${this.lastID}`);
}
});
}
});
### 总结
- 使用`db.exec`当你只需要执行 SQL 语句而不关心返回信息时。
- 使用`db.run`当你需要执行 SQL 语句并希望获取执行状态或返回的行信息时。
static/image/hrline/1.gif
sqlcipher中insert多字段插入在 SQLCipher 中,插入多字段数据的 SQL 语句与标准 SQLite 的语法相同。你可以使用`INSERT INTO`语句来插入多个字段的数据。以下是一个示例,展示如何在 SQLCipher 中插入多字段数据。
### 示例代码
const sqlite3 = require('sqlite3').verbose();
const SQLCipher = require('sqlcipher');
// 创建或打开数据库
let db = new SQLCipher.Database('test.db');
// 使用密码打开数据库
db.exec("PRAGMA key = 'your_password';", (err) => {
if (err) {
console.error(err.message);
} else {
// 创建表
db.exec("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER);", (err) => {
if (err) {
console.error(err.message);
} else {
// 插入多字段数据
const sql = "INSERT INTO users (name, age) VALUES (?, ?)";
const params = ['Alice', 30];
db.run(sql, params, function(err) {
if (err) {
console.error(err.message);
} else {
console.log(`Inserted row with ID: ${this.lastID}`);
}
});
}
});
}
});
// 关闭数据库
db.close();
### 说明
1. **创建或打开数据库**:使用`new SQLCipher.Database('test.db')`创建或打开一个数据库文件。
2. **设置密码**:使用`PRAGMA key = 'your_password';`设置数据库的密码。
3. **创建表**:使用`CREATE TABLE`语句创建一个名为`users`的表,包含`id` 、 `name`和`age`三个字段。
4. **插入数据**:
- 使用`INSERT INTO`语句插入多字段数据。
- 使用占位符`?`来防止 SQL 注入,并将实际的值通过`params`数组传递。
5. **获取插入的行 ID**:通过`this.lastID`获取插入数据后生成的行 ID。
这个示例展示了如何在 SQLCipher 中插入多字段数据。
页:
[1]