nodejs mysql框架 nodejs操作mysql数据库
时间: 2023-11-21 10:56:17 浏览: 215
以下是使用Node.js操作MySQL数据库的示例代码:
1.安装mysql模块
```shell
npm install mysql
```
2.连接MySQL数据库
```javascript
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!');
});
```
3.创建数据库
```javascript
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected!');
connection.query('CREATE DATABASE test', (err, result) => {
if (err) throw err;
console.log('Database created!');
});
});
```
4.创建表
```javascript
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!');
const sql = 'CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))';
connection.query(sql, (err, result) => {
if (err) throw err;
console.log('Table created!');
});
});
```
5.插入数据
```javascript
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!');
const sql = 'INSERT INTO customers (name, address) VALUES ("Company Inc", "Highway 37")';
connection.query(sql, (err, result) => {
if (err) throw err;
console.log('1 record inserted');
});
});
```
6.查询数据
```javascript
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!');
const sql = 'SELECT * FROM customers';
connection.query(sql, (err, result) => {
if (err) throw err;
console.log(result);
});
});
```
阅读全文
相关推荐

















