node.js how to use sqlite
时间: 2023-11-08 09:59:55 浏览: 45
Sure, you can use the "sqlite3" module in Node.js to interact with a SQLite database. First, you need to install the module by running the command "npm install sqlite3" in your terminal. Then, you can create a new SQLite database or connect to an existing one using the "sqlite3.Database" class. From there, you can execute SQL queries using the "run", "get", and "all" methods.
Here's an example of how you can create a new database, create a table, insert some data, and query it:
```
const sqlite3 = require('sqlite3').verbose();
// create a new database
const db = new sqlite3.Database('mydb.sqlite');
// create a table
db.run('CREATE TABLE users (id INT PRIMARY KEY, name TEXT)');
// insert some data
db.run('INSERT INTO users (id, name) VALUES (?, ?)', [1, 'Alice']);
db.run('INSERT INTO users (id, name) VALUES (?, ?)', [2, 'Bob']);
// query the data
db.all('SELECT * FROM users', (err, rows) => {
if (err) {
console.error(err);
} else {
console.log(rows);
}
});
// close the database connection
db.close();
```
This example creates a new database file called "mydb.sqlite", creates a "users" table with two columns (id and name), inserts two rows of data, queries all the rows from the table, and prints the result to the console.
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)