SQLite 3 Database Management and Usage
SQLite 3 is a lightweight, embedded relational database management system widely used in mobile applications, embedded systems, and small desktop applications. SQLite 3 does not require a separate server process, with data stored in a single file, making it easy to manage and use. This article provides a detailed introduction on how to manage and use SQLite 3 databases in ServBay, including installation, configuration, backup, restoration, and performance optimization.
Installing and Configuring SQLite 3
ServBay comes with SQLite 3, which can be used directly in environments like command line, PHP, Node.js, etc.
Verifying SQLite 3 Installation
You can verify if SQLite 3 is installed by using the following command:
sqlite3 --version
If version information is displayed, it indicates that SQLite 3 is installed.
Creating and Connecting to SQLite 3 Database
SQLite 3 databases are stored in a single file, with the default path being /Applications/ServBay/db/sqlite
. You can use the command-line tool sqlite3
or SQLite libraries in programming languages to create and connect to databases.
Connecting Using Command-Line Tool
Create or Connect to Database:
bashsqlite3 /Applications/ServBay/db/sqlite/your_database.db
1Exit SQLite 3:
sql.exit
1
Connecting Using Programming Languages
PHP Example
Using the SQLite3
class to connect to SQLite 3:
<?php
// Connect to SQLite 3 database
$db = new SQLite3('/Applications/ServBay/db/sqlite/your_database.db');
// Create table
$db->exec("CREATE TABLE IF NOT EXISTS mytable (id INTEGER PRIMARY KEY, name TEXT)");
// Insert data
$db->exec("INSERT INTO mytable (name) VALUES ('Alice')");
// Query data
$result = $db->query("SELECT * FROM mytable");
while ($row = $result->fetchArray()) {
echo "ID: " . $row['id'] . " Name: " . $row['name'] . "\n";
}
// Close database connection
$db->close();
?>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Node.js Example
Using the sqlite3
library to connect to SQLite 3:
const sqlite3 = require('sqlite3').verbose();
// Connect to SQLite 3 database
let db = new sqlite3.Database('/Applications/ServBay/db/sqlite/your_database.db', (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the SQLite database.');
});
// Create table
db.run(`CREATE TABLE IF NOT EXISTS mytable (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT
)`);
// Insert data
db.run(`INSERT INTO mytable (name) VALUES (?)`, ['Alice'], function(err) {
if (err) {
return console.error(err.message);
}
console.log(`A row has been inserted with rowid ${this.lastID}`);
});
// Query data
db.all(`SELECT * FROM mytable`, [], (err, rows) => {
if (err) {
throw err;
}
rows.forEach((row) => {
console.log(row.id, row.name);
});
});
// Close database connection
db.close((err) => {
if (err) {
console.error(err.message);
}
console.log('Close the database connection.');
});
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
Database Management
Basic Operations
Create Table:
sqlCREATE TABLE mytable (id INTEGER PRIMARY KEY, name TEXT);
1Insert Data:
sqlINSERT INTO mytable (name) VALUES ('Alice');
1Query Data:
sqlSELECT * FROM mytable;
1Update Data:
sqlUPDATE mytable SET name = 'Bob' WHERE id = 1;
1Delete Data:
sqlDELETE FROM mytable WHERE id = 1;
1
Backup and Restore
Backup Database
SQLite 3 databases are stored in a single file, so backups simply involve copying this file. It is recommended to store backup files in the following directory:
/Applications/ServBay/backup/sqlite
Use the command-line tool to copy the database file for backup:
cp /Applications/ServBay/db/sqlite/your_database.db /Applications/ServBay/backup/sqlite/your_database_backup.db
Restore Database
Copy the backup file back to the original location to restore:
cp /Applications/ServBay/backup/sqlite/your_database_backup.db /Applications/ServBay/db/sqlite/your_database.db
Performance Optimization
SQLite 3 offers various performance optimization options. Here are some common optimization methods.
Index Optimization
Ensure that indexes are created for columns frequently queried. For example:
CREATE INDEX idx_name ON mytable(name);
Query Optimization
Use the EXPLAIN
command to analyze query performance and perform corresponding optimizations. For example:
EXPLAIN QUERY PLAN SELECT * FROM mytable WHERE name = 'Alice';
Configuration Optimization
Adjust SQLite 3's PRAGMA parameters to improve performance. For example, enable synchronous mode to improve write performance:
PRAGMA synchronous = OFF;
Security Management
Ensuring the security of the database is crucial. Here are some security management suggestions.
File Permissions
Ensure the correct setting of permissions for the SQLite 3 database file to prevent unauthorized access. For example:
chmod 600 /Applications/ServBay/db/sqlite/your_database.db
Data Encryption
SQLite 3 supports database encryption. You can use SQLite encryption extensions (such as SQLCipher) to encrypt the database.
Common Issues and Solutions
Cannot Connect to SQLite 3 Database
Check Database File Path: Ensure the database file path is correct and the file exists.
Check File Permissions: Ensure the file permissions allow read and write operations.
Database Locked
Check Concurrent Access: Ensure no other processes are accessing the database, as SQLite 3 locks the database during write operations.
Use WAL Mode: Enable Write-Ahead Logging (WAL) mode to improve concurrent performance:
sqlPRAGMA journal_mode = WAL;
1
Summary
SQLite 3 is a powerful and flexible embedded database management system. ServBay includes SQLite 3, making database management and usage more convenient. With this introduction, you can easily perform the installation, configuration, connection, management, backup, restoration, and optimization of SQLite 3, ensuring efficient operation and security of your database.