在Node.js中执行SQL查询的常见做法是使用数据库连接库(如mysql,pg等)来连接数据库并执行SQL查询。下面是一些在Node.js中执行SQL查询的技巧:
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydatabase'
});
connection.connect();
const query = (sql) => {
return new Promise((resolve, reject) => {
connection.query(sql, (error, results) => {
if (error) {
reject(error);
} else {
resolve(results);
}
});
});
};
(async () => {
try {
const results = await query('SELECT * FROM mytable');
console.log(results);
} catch (error) {
console.error(error);
} finally {
connection.end();
}
})();
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydatabase'
});
connection.connect();
const query = (sql, values) => {
return new Promise((resolve, reject) => {
connection.query(sql, values, (error, results) => {
if (error) {
reject(error);
} else {
resolve(results);
}
});
});
};
(async () => {
try {
const results = await query('SELECT * FROM mytable WHERE id = ?', [1]);
console.log(results);
} catch (error) {
console.error(error);
} finally {
connection.end();
}
})();
const mysql = require('mysql');
const pool = mysql.createPool({
connectionLimit : 10,
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydatabase'
});
const query = (sql, values) => {
return new Promise((resolve, reject) => {
pool.query(sql, values, (error, results) => {
if (error) {
reject(error);
} else {
resolve(results);
}
});
});
};
(async () => {
try {
const results = await query('SELECT * FROM mytable WHERE id = ?', [1]);
console.log(results);
} catch (error) {
console.error(error);
}
})();
这些是在Node.js中执行SQL查询的一些常见技巧,希望对您有所帮助。