使用Node操作MySQL的兩種方式
使用 mysql2 庫(kù)操作 MySQL
mysql2 是 mysql 庫(kù)的升級(jí)版,提供了更多特性,并且支持 Promise API。以下是使用 mysql2 進(jìn)行數(shù)據(jù)庫(kù)操作的基本步驟:
安裝和配置
創(chuàng)建項(xiàng)目目錄,初始化 npm,并安裝 mysql2:
mkdir myproject cd myproject npm init -y npm install --save mysql2
創(chuàng)建 index.js 文件,并配置數(shù)據(jù)庫(kù)連接:
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'root',
password: 'your_password',
database: 'practice'
});
基本操作
查詢操作
connection.query('SELECT * FROM customers', (err, results, fields) => {
if (err) throw err;
console.log(results);
console.log(fields.map(item => item.name));
});
插入數(shù)據(jù)
connection.execute('INSERT INTO customers (name) VALUES (?)', ['Zhang'], (err, results) => {
if (err) throw err;
console.log('Insert successful');
});
更新數(shù)據(jù)
connection.execute('UPDATE customers SET name="Li" WHERE name="Zhang"', (err) => {
if (err) throw err;
console.log('Update successful');
});
刪除數(shù)據(jù)
connection.execute('DELETE FROM customers WHERE name="Li"', (err) => {
if (err) throw err;
console.log('Delete successful');
});
使用連接池提高性能
連接池可以管理多個(gè)數(shù)據(jù)庫(kù)連接,提高應(yīng)用性能和響應(yīng)速度:
const mysql = require('mysql2/promise');
(async () => {
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'your_password',
database: 'practice',
waitForConnections: true, // 如果沒(méi)有可用連接,等待而不是立即拋出錯(cuò)誤
connectionLimit: 10, // 連接池中最大連接數(shù)
queueLimit: 0 // 最大排隊(duì)數(shù)量,0表示不限制
});
const [results] = await pool.query('SELECT * FROM customers');
console.log(results);
})();
使用 TypeORM 框架操作 MySQL
TypeORM 是一個(gè)基于 TypeScript 的 ORM (對(duì)象關(guān)系映射) 框架,它可以讓開(kāi)發(fā)者通過(guò)操作對(duì)象而不是 SQL 語(yǔ)句來(lái)處理數(shù)據(jù)庫(kù)。
項(xiàng)目設(shè)置
創(chuàng)建并配置新項(xiàng)目:
npx typeorm@latest init --name typeorm-mysql-test --database mysql
在 data-source.ts 中配置數(shù)據(jù)庫(kù):
import { DataSource } from 'typeorm';
import { User } from './entity/User';
export const AppDataSource = new DataSource({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'your_password',
database: 'practice',
synchronize: true,
entities: [User],
connectorPackage: 'mysql2'
});
操作數(shù)據(jù)庫(kù)
使用裝飾器定義模型(Entity):
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
}
插入和查詢數(shù)據(jù)
import { AppDataSource } from './data-source';
import { User } from './entity/User';
AppDataSource.initialize().then(async () => {
const user = new User();
user.name = 'Wang';
await AppDataSource.manager.save(user);
const users = await AppDataSource.manager.find(User);
console.log(users);
});
優(yōu)點(diǎn)
使用 ORM 框架可以大大簡(jiǎn)化數(shù)據(jù)庫(kù)操作,使代碼更加直觀和易于維護(hù)。同時(shí),TypeORM 提供了強(qiáng)大的數(shù)據(jù)模型管理功能,支持自動(dòng)創(chuàng)建表、生成 SQL 語(yǔ)句等。
到此這篇關(guān)于使用Node操作MySQL的兩種方式的文章就介紹到這了,更多相關(guān)Node操作MySQL內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
pm2發(fā)布node配置文件ecosystem.json詳解
這篇文章主要介紹了pm2發(fā)布node配置文件ecosystem.json詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-05-05
vscode無(wú)法運(yùn)行npm命令的問(wèn)題解決(cmd可行)
本文主要介紹了vscode無(wú)法運(yùn)行npm命令的問(wèn)題解決(cmd可行),VSCode無(wú)法調(diào)用npm可能是因?yàn)榄h(huán)境路徑配置錯(cuò)誤,下面就來(lái)具體介紹一下原因及解決方法,感興趣的可以了解一下2024-04-04
node.js中的path.resolve方法使用說(shuō)明
這篇文章主要介紹了node.js中的path.resolve方法使用說(shuō)明,本文介紹了path.resolve的方法說(shuō)明、接收參數(shù)、語(yǔ)法、使用實(shí)例和實(shí)現(xiàn)源碼,需要的朋友可以參考下2014-12-12
NodeJS 將文件夾按照存放路徑變成一個(gè)對(duì)應(yīng)的JSON的方法
這篇文章主要介紹了NodeJS 將文件夾按照存放路徑變成一個(gè)對(duì)應(yīng)的JSON的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-10-10
Nodejs使用archiver-zip-encrypted庫(kù)加密壓縮文件時(shí)報(bào)錯(cuò)(解決方案)
這篇文章主要介紹了Nodejs使用archiver-zip-encrypted庫(kù)加密壓縮文件時(shí)報(bào)錯(cuò),朋友朋友在測(cè)試過(guò)程中都出現(xiàn)過(guò)異常,下面小編把問(wèn)題過(guò)程分析腳本之家平臺(tái),需要的朋友可以參考下2019-11-11
yarn?install命令報(bào)錯(cuò)warning?package-lock.json?found解決辦法
這篇文章主要給大家介紹了關(guān)于yarn?install命令報(bào)錯(cuò)warning?package-lock.json?found的解決辦法,文中通過(guò)圖文將解決的辦法介紹的非常詳細(xì),還分享了更多yarn install遇到的報(bào)錯(cuò)及解決方案,需要的朋友可以參考下2024-02-02

