在当今的互联网时代,JavaScript(JS)已经成为前端开发的主流语言。随着Node.js的兴起,JavaScript也逐渐涉足后端领域。而数据库作为存储数据的重要工具,对于开发者来说至关重要。本文将带你轻松掌握JS读取数据库的全攻略,包括MySQL、MongoDB、SQLite等常见数据库的操作技巧。
MySQL数据库操作
MySQL是一种关系型数据库,广泛应用于各种场景。在Node.js中,我们可以使用mysql模块来操作MySQL数据库。
安装mysql模块
首先,我们需要安装mysql模块:
npm install mysql
连接MySQL数据库
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'test'
});
connection.connect(err => {
if (err) throw err;
console.log('Connected to the MySQL server!');
});
查询数据
const query = 'SELECT * FROM users';
connection.query(query, (err, results, fields) => {
if (err) throw err;
console.log(results);
});
关闭连接
connection.end(err => {
if (err) throw err;
console.log('Disconnected from the MySQL server.');
});
MongoDB数据库操作
MongoDB是一种文档型数据库,具有灵活的数据结构。在Node.js中,我们可以使用mongodb模块来操作MongoDB数据库。
安装mongodb模块
首先,我们需要安装mongodb模块:
npm install mongodb
连接MongoDB数据库
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'test';
MongoClient.connect(url, { useUnifiedTopology: true }, (err, client) => {
if (err) throw err;
console.log('Connected to the MongoDB server!');
const db = client.db(dbName);
const collection = db.collection('users');
// 查询数据
collection.find({}).toArray((err, docs) => {
if (err) throw err;
console.log(docs);
});
// 关闭连接
client.close();
});
SQLite数据库操作
SQLite是一种轻量级的关系型数据库,常用于移动应用和桌面应用。在Node.js中,我们可以使用sqlite3模块来操作SQLite数据库。
安装sqlite3模块
首先,我们需要安装sqlite3模块:
npm install sqlite3
连接SQLite数据库
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database(':memory:');
db.serialize(() => {
db.run('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)');
db.run('INSERT INTO users (name) VALUES (?)', ['Alice']);
db.run('INSERT INTO users (name) VALUES (?)', ['Bob']);
db.all('SELECT rowid AS id, name FROM users', [], (err, rows) => {
if (err) throw err;
rows.forEach((row) => {
console.log(`${row.id}: ${row.name}`);
});
});
});
db.close();
总结
通过本文的学习,相信你已经掌握了在Node.js中操作MySQL、MongoDB、SQLite等数据库的方法。在实际开发过程中,你可以根据项目需求选择合适的数据库,并灵活运用这些操作技巧。祝你编程愉快!
