Hampir setiap bahasa pemrograman populer, seperti PHP, Java, C# dll menyediakan driver untuk koneksi dengan database MySql. Karena MySQL adalah salah satu database open source paling populer di dunia dan juga efisien, perlu ada dukungan untuk itu di Node. js dan berkat modul ini, Anda akan dapat mengakses dari Node. js tanpa masalah apa pun. Kita berbicara tentang modul mysql, sebuah node. driver js untuk mysql. Itu ditulis dalam JavaScript, tidak memerlukan kompilasi, dan 100% berlisensi MIT
Pada artikel ini Anda akan belajar cara terhubung ke database apa pun di server MySQL Anda dengan mudah menggunakan Node. js dalam beberapa menit
Persyaratan
Untuk beroperasi dengan MySQL (dalam kasus kami, kami menggunakan Xampp yang menyertakan PHPMyAdmin) menggunakan Node. js, Anda memerlukan paket node berikut bernama mysql
Anda dapat menambahkan paket ini ke proyek Anda dengan menjalankan perintah berikut di Node. prompt perintah js
npm install mysqlKemudian Anda dapat meminta modul mysql
Catatan. modul ini pengecualian aman. Itu berarti Anda dapat terus menggunakannya, bahkan jika salah satu fungsi panggilan balik Anda melontarkan kesalahan yang Anda tangkap menggunakan 'uncaughtException' atau domain
Penerapan
Ada 2 cara untuk mengakses database MySQL, Anda dapat memilih koneksi sederhana untuk mengakses dengan cepat ketika Anda hanya memiliki 1 database. Anda harus menggunakan koneksi gabungan untuk memudahkan berbagi satu koneksi, atau mengelola banyak koneksi
Koneksi sederhana
Contoh berikut memaparkan koneksi dengan komponen paling dasarnya. Memerlukan layanan mysql, tambahkan kredensial sebagai parameter pertama dalam metode createConnection, lanjutkan untuk menyambung ke database, melakukan kueri, dan terakhir menutup koneksi
Anda dapat membaca semua opsi yang tersedia untuk objek koneksi di
// Get the mysql service var mysql = require('mysql'); // Add the credentials to access your database var connection = mysql.createConnection({ host : 'localhost', user : '<USERNAME that tipically is root>', password : '<PASSWORD or just use null if youre working lcocally', database : '<DATABASE-NAME>' }); // connect to mysql connection.connect(function(err) { // in case of error if(err){ console.log(err.code); console.log(err.fatal); } }); // Perform a query $query = 'SELECT * from MyTable LIMIT 10'; connection.query($query, function(err, rows, fields) { if(err){ console.log("An error ocurred performing the query."); return; } console.log("Query succesfully executed: ", rows); }); // Close the connection connection.end(function(){ // The connection has been closed }); _Koneksi gabungan
var mysql = require('mysql'); var pool = mysql.createPool({ host : 'example.org', user : 'bob', password : 'secret', database : 'my_dbName' }); pool.getConnection(function(err, connection) { // Use the connection connection.query( 'SELECT something FROM sometable', function(err, rows) { // And done with the connection. connection.release(); // Don't use the connection here, it has been returned to the pool. }); }); // The pool will emit a connection event when a new connection is made within the pool. // If you need to set session variables on the connection before it gets used, you can listen to the connection event. pool.on('connection', function (connection) { console.log("Connected"); // Set a session variable //connection.query('SET SESSION auto_increment_increment=1') }); // <<< CLOSE THE CONNECTION USING pool.end >>> // When you are done using the pool, you have to end all the connections or the Node.js // event loop will stay active until the connections are closed by the MySQL server. // This is typically done if the pool is used in a script or when trying to gracefully shutdown a server. // To end all the connections in the pool, use the end method on the pool: pool.end(function (err) { // all connections in the pool have ended });Kiat
Anda dapat menggunakan wildcard untuk membuat kode yang mudah dibaca dan dipelihara
connection.query('SELECT * FROM `books` WHERE `author` = ?', ['David'], function (error, results, fields) { // error will be an Error if one occurred during the query // results will contain the results of the query // fields will contain information about the returned results fields (if any) });Selain meneruskan opsi ini sebagai objek, Anda juga dapat menggunakan string url untuk koneksi. Sebagai contoh
var connection = mysql.createConnection('mysql://user:[email protected]/db?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700');_Untuk menghindari serangan SQL Injection, Anda harus selalu menghindari data yang disediakan pengguna sebelum menggunakannya di dalam kueri SQL. Anda dapat melakukannya dengan menggunakan metode mysql.escape(), connection.escape() atau pool.escape()