MySQL से Connect करना
mysql2 package आपकी Node app को एक MySQL database से connect करता है और queries चलाता है।
In this page:
Syntax
const mysql = require('mysql2/promise');
const connection = await mysql.createConnection({
host: 'host', user: 'user', password: 'password', database: 'database'
});
const [rows] = await connection.execute('SELECT * FROM table_name WHERE column = ?', [value]);
MySQL से Connect करना
mysql2 install करें, host, user, password, और database के साथ एक connection या pool बनाएँ, फिर query या execute call करें। SQL injection से बचने के लिए execute के साथ placeholders (?) इस्तेमाल करें। हमेशा connections close करें या एक pool इस्तेमाल करें।
Note:
? placeholders वाले Prepared statements SQL injection रोकते हैं।
उदाहरण: Connecting to MySQL
$ npm install mysql2
const mysql = require("mysql2/promise");
const pool = mysql.createPool({ host: "localhost", user: "app", password: process.env.DB_PASS, database: "shop" });
const [rows] = await pool.execute("SELECT id, name FROM users WHERE id = ?", [1]);
console.log(rows[0]);
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- string concatenation से SQL बनाना
- connections close न करना
- credentials hard-code करना
चैप्टर सारांश
- mysql2 install करें
- एक pool बनाएँ
- Placeholders इस्तेमाल करें
- Connections close या reuse करें
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: