sqlite nodejs
SQLite is a powerful database that lives in a single file or in memory and gives us all the basic operations (queries, views, triggers, indexes, etc) that have big enterprise databases such as MySQL, Postgress, etc…
SQLite是一个功能强大的数据库,位于单个文件或内存中,并为我们提供了具有大型企业数据库(如MySQL,Postgress等)的所有基本操作(查询,视图,触发器,索引等)…
In nodejs, we have a sqlite3
module that gives us all the features we need to interact with an SQLite database.
在nodejs中,我们有一个sqlite3
模块,该模块为我们提供了与SQLite数据库进行交互所需的所有功能。
1.安装sqlite3
并连接数据库 (1. Install sqlite3
and connect with the database)
In this section, we will create users.db database, establish, and close a connection with users.db.
在本节中,我们将创建users.db数据库,建立并关闭与users.db的连接。
Create a new nodejs project
创建一个新的nodejs项目
cd sqliteBasics
npm init -y
npm i sqlite3
Now create an ./index.js file
现在创建一个./index.js文件
2.创建表,插入和检索数据 (2. Create table, insert and retrieve data)
The task is to create a users
table with 2 columns (username, password) then insert and retrieve data. But in nodejs framework serial operations are tricky. Don’t freak out sqlite3
has db.serialize() function that gives us the power to serialize our query statements.
任务是创建一个包含两列(用户名,密码)的users
表,然后插入和检索数据。 但是在nodejs框架中,串行操作比较棘手。 不要害怕sqlite3
具有db.serialize()函数,该函数使我们能够序列化查询语句。
We are going to use 3 main functions :
我们将使用3个主要功能:
db.serialize([callback]) Inside the callback method we can run operations in serial order.
db.serialize([callback])在回调方法中,我们可以按顺序运行操作。
db.run(SQL,[param, …], [callback]) Run SQL statement but not retrieve any data.
db.run(SQL,[param,…],[callback])运行SQL语句,但不检索任何数据。
db.each(SQL, [param, …], [callback], [complete]) Run SQL statement retrieve the data from query and loop each row separately.
db.each(SQL,[param,…],[callback],[complete])运行SQL语句从查询中检索数据并分别循环每一行。
Update ./index.js file
更新./index.js文件
3.更新和删除数据 (3. Update and Delete data)
Now that we have the users.db database with data, we can run an update and delete queries.
现在我们有了包含数据的users.db数据库,我们可以运行更新和删除查询。
Create a new file ./updateDelete.js
创建一个新文件./updateDelete.js
结论 (Conclusion)
This was a quick lesson withsqlite3
module on how to:
这是sqlite3
模块的快速课程,内容如下:
- Open-close connection with the database 与数据库的开闭连接
Run CRUD (Create, Update, Delete) queries
运行CRUD (创建,更新,删除)查询
Set the flow in serial mode with db.serialize([callback]) method
使用db.serialize([callback])方法以串行方式设置流
翻译自: https://levelup.gitconnected.com/learn-basic-operations-with-sqlite-and-nodejs-a693c6fc2e15
sqlite nodejs