41 lines
1,022 B
JavaScript
41 lines
1,022 B
JavaScript
|
|
const mysql = require('mysql2/promise');
|
||
|
|
require('dotenv').config();
|
||
|
|
|
||
|
|
const pool = mysql.createPool({
|
||
|
|
host: process.env.DB_HOST || '127.0.0.1',
|
||
|
|
port: Number(process.env.DB_PORT || 3306),
|
||
|
|
user: process.env.DB_USER,
|
||
|
|
password: process.env.DB_PASS,
|
||
|
|
database: process.env.DB_NAME,
|
||
|
|
waitForConnections: true,
|
||
|
|
connectionLimit: 10,
|
||
|
|
charset: 'utf8mb4_general_ci',
|
||
|
|
dateStrings: true,
|
||
|
|
});
|
||
|
|
|
||
|
|
// Mehrere Zeilen
|
||
|
|
async function q(sql, params = []) {
|
||
|
|
const [rows] = await pool.query(sql, params);
|
||
|
|
return rows;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Genau eine Zeile (oder null)
|
||
|
|
async function q1(sql, params = []) {
|
||
|
|
const rows = await q(sql, params);
|
||
|
|
return rows[0] || null;
|
||
|
|
}
|
||
|
|
|
||
|
|
// INSERT -> insertId
|
||
|
|
async function insert(sql, params = []) {
|
||
|
|
const [res] = await pool.query(sql, params);
|
||
|
|
return res.insertId;
|
||
|
|
}
|
||
|
|
|
||
|
|
// UPDATE/DELETE -> affectedRows
|
||
|
|
async function exec(sql, params = []) {
|
||
|
|
const [res] = await pool.query(sql, params);
|
||
|
|
return res.affectedRows;
|
||
|
|
}
|
||
|
|
|
||
|
|
module.exports = { pool, q, q1, insert, exec };
|