在Node.js中執(zhí)行SQL查詢的常見做法是使用數(shù)據(jù)庫連接庫(如mysql,pg等)來連接數(shù)據(jù)庫并執(zhí)行SQL查詢。下面是一些在Node.js中執(zhí)行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中執(zhí)行SQL查詢的一些常見技巧,希望對您有所幫助。