js中连接数据库的方法
- 格式:doc
- 大小:36.82 KB
- 文档页数:4
js中连接数据库的方法
在JavaScript中,通常我们使用来连接数据库。以下是一些常见的数据库和如何使用连接它们的方法:
1. MySQL
使用`mysql`模块:
```javascript
const mysql = require('mysql');
const connection = ({
host: 'localhost',
user: 'root',
password: 'password',
database: 'my_db'
});
((err) => { if (err) throw err;
('Connected to the MySQL server.');
});
```
2. MongoDB
使用`mongodb`模块:
```javascript
const MongoClient = require('mongodb').MongoClient;
const url = "
(url, function(err, db) {
if (err) throw err;
('Connected to MongoDB server.');
();
});
```
3. PostgreSQL
使用`pg`模块:
```javascript
const { Pool } = require('pg')
const pool = new Pool({
user: 'myuser',
host: 'localhost',
database: 'mydb',
password: 'mypassword',
port: 5432,
})
((err, client) => {
if (err) throw err;
('Connected to PostgreSQL server.');
()
})
```
4. SQLite
使用`sqlite3`模块:
```javascript
const sqlite3 = require('sqlite3').verbose(); // Use verbose mode to
enable debug output
const db = new (':memory:'); // Create a in-memory database. You
can also specify a filename instead of ':memory:' to persist data to
disk.
(function() {
("SELECT rowid AS id, name FROM lorem", function(err, row) {
( + ": " + );
});
});
();
```
请注意,这些示例假设您已经正确地安装了相应的数据库和模块。此外,对于生产环境,您可能需要更复杂的错误处理和连接池设置。