### Installing mysql Node.js module via npm Source: https://github.com/mysqljs/mysql/blob/master/Readme.md This command installs the official mysql Node.js driver from the npm registry. It is the standard way to add the module to your project dependencies. ```sh $ npm install mysql ``` -------------------------------- ### Installing mysql Node.js module from GitHub Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Use this command to install the latest version of the mysql driver directly from the mysqljs/mysql GitHub repository. This is often used for testing bug fixes or new features before they are released on npm. ```sh $ npm install mysqljs/mysql ``` -------------------------------- ### Establishing and Querying MySQL Connection in Node.js Source: https://github.com/mysqljs/mysql/blob/master/Readme.md This example demonstrates how to establish a connection to a MySQL database, execute a simple SELECT query, and handle the results. It shows the basic flow of requiring the module, creating a connection, connecting, querying, and ending the connection. Methods are queued and executed sequentially. ```js var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'me', password : 'secret', database : 'my_db' }); connection.connect(); connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) { if (error) throw error; console.log('The solution is: ', results[0].solution); }); connection.end(); ``` -------------------------------- ### Handling MySQL Pool 'connection' Event - Node.js Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Demonstrates how to listen for the 'connection' event, which is emitted when a *new* connection is established within the pool. This is the appropriate place to set session variables or perform initial setup on fresh connections. ```js pool.on('connection', function (connection) { connection.query('SET SESSION auto_increment_increment=1') }); ``` -------------------------------- ### Defining Custom Query Format Function in mysql Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Provides an example of how to set a custom `queryFormat` function on the connection configuration to handle alternative placeholder syntaxes (like `:name`) for query preparation. ```js connection.config.queryFormat = function (query, values) { if (!values) return query; return query.replace(/\:(\w+)/g, function (txt, key) { if (values.hasOwnProperty(key)) { return this.escape(values[key]); } return txt; }.bind(this)); }; connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" }); ``` -------------------------------- ### Configuring MySQL PoolCluster Options (Node.js) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Shows how to initialize a PoolCluster with custom configuration options. This example sets `removeNodeErrorCount` to 1, causing a node to be removed immediately upon a connection failure, and sets the `defaultSelector` to 'ORDER', which attempts to connect to nodes in the order they are listed. ```javascript var clusterConfig = { removeNodeErrorCount: 1, // Remove the node immediately when connection fails. defaultSelector: 'ORDER' }; var poolCluster = mysql.createPoolCluster(clusterConfig); ``` -------------------------------- ### Executing Multiple Statements (mysqljs) - JavaScript Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Provides an example of executing a query string containing multiple SQL statements after enabling the `multipleStatements` option. Explains that the callback receives an array of results, one element for each statement executed. ```javascript connection.query('SELECT 1; SELECT 2', function (error, results, fields) { if (error) throw error; // `results` is an array with one element for every statement in the query: console.log(results[0]); // [{1: 1}] console.log(results[1]); // [{2: 2}] }); ``` -------------------------------- ### Getting and Releasing MySQL Pool Connection - Node.js Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Illustrates the explicit flow of acquiring a connection from the pool using `pool.getConnection()`, executing a query on the connection, and releasing it back to the pool using `connection.release()`. This is useful for maintaining connection state across multiple sequential queries. ```js var mysql = require('mysql'); var pool = mysql.createPool(...); pool.getConnection(function(err, connection) { if (err) throw err; // not connected! // Use the connection connection.query('SELECT something FROM sometable', function (error, results, fields) { // When done with the connection, release it. connection.release(); // Handle error after the release. if (error) throw error; // Don't use the connection here, it has been returned to the pool. }); }); ``` -------------------------------- ### Getting MySQL Connection ID (threadId) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Shows how to access the `connection.threadId` property to retrieve the unique connection ID assigned by the MySQL server. ```js connection.connect(function(err) { if (err) throw err; console.log('connected as id ' + connection.threadId); }); ``` -------------------------------- ### Getting Number of Changed Rows after mysql UPDATE Query Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Explains and demonstrates how to get the count of rows whose values were actually modified by an UPDATE statement using the `results.changedRows` property, which differs from `affectedRows`. ```js connection.query('UPDATE posts SET ...', function (error, results, fields) { if (error) throw error; console.log('changed ' + results.changedRows + ' rows'); }) ``` -------------------------------- ### Suppressing Unhandled Errors (JavaScript) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Provides an example of attaching an empty listener to the 'error' event on the connection object. This prevents the default behavior of crashing the process when an unhandled error event occurs, effectively suppressing the error. ```js // I am Chuck Norris: connection.on('error', function() {}); ``` -------------------------------- ### Getting Number of Affected Rows after mysql Query Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Shows how to retrieve the total number of rows affected by DML statements (INSERT, UPDATE, DELETE) using the `results.affectedRows` property in the query callback. ```js connection.query('DELETE FROM posts WHERE title = "wrong"', function (error, results, fields) { if (error) throw error; console.log('deleted ' + results.affectedRows + ' rows'); }) ``` -------------------------------- ### Getting Inserted Row ID after mysql INSERT Query Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Demonstrates how to access the `results.insertId` property in the query callback to retrieve the auto-generated primary key value after a successful INSERT statement. ```js connection.query('INSERT INTO posts SET ?', {title: 'test'}, function (error, results, fields) { if (error) throw error; console.log(results.insertId); }); ``` -------------------------------- ### Establishing MySQL Connection using connect (Node.js) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Demonstrates the recommended way to establish a connection to a MySQL database using the `mysql` module in Node.js. It requires the `mysql` module and uses `createConnection` to configure connection parameters, followed by explicitly calling `connection.connect` to initiate the connection. Includes basic error handling. ```JavaScript var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'example.org', user : 'bob', password : 'secret' }); connection.connect(function(err) { if (err) { console.error('error connecting: ' + err.stack); return; } console.log('connected as id ' + connection.threadId); }); ``` -------------------------------- ### Running Integration Tests with npm Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Executes the integration test suite. This requires a running MySQL server. The first command creates a test database using the mysql client. The second command runs `npm test`, setting environment variables to configure the connection details and specifying `FILTER=integration` to run only integration tests. ```sh $ mysql -u root -e "CREATE DATABASE IF NOT EXISTS node_mysql_test" $ MYSQL_HOST=localhost MYSQL_PORT=3306 MYSQL_DATABASE=node_mysql_test MYSQL_USER=root MYSQL_PASSWORD= FILTER=integration npm test ``` -------------------------------- ### Creating and Querying MySQL Connection in Node.js Source: https://github.com/mysqljs/mysql/blob/master/Changes.md This snippet demonstrates how to establish a connection to a MySQL database using the new `Connection` class in mysqljs/mysql v2.0.0-alpha, execute a simple query, handle potential errors, and close the connection. It replaces the older `mysql.createClient()` method. ```js var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'me', password : 'secret', }); connection.query('SELECT 1', function(err, rows) { if (err) throw err; console.log('Query result: ', rows); }); connection.end(); ``` -------------------------------- ### Performing Basic SQL Query with mysqljs/mysql (JS) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Demonstrates the simplest form of the `.query()` method, executing a raw SQL string directly. It shows how to handle the callback with error, results, and fields parameters. ```js 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) }); ``` -------------------------------- ### Creating and Querying MySQL Pool Directly - Node.js Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Demonstrates how to create a MySQL connection pool using `mysql.createPool()` and execute a query directly on the pool using `pool.query()`. This is a shortcut for acquiring, querying, and releasing a connection. ```js var mysql = require('mysql'); var pool = mysql.createPool({ connectionLimit : 10, host : 'example.org', user : 'bob', password : 'secret', database : 'my_db' }); pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) { if (error) throw error; console.log('The solution is: ', results[0].solution); }); ``` -------------------------------- ### Using MySQL PoolCluster (Node.js) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Illustrates the creation and basic usage of a PoolCluster for managing connections across multiple MySQL hosts. It shows how to add named and automatic configurations, remove nodes, obtain connections using different target groups and selectors (round-robin, order, random, patterns), use the `of` method, execute queries via a cluster-derived pool, and finally end the entire cluster. ```javascript // create var poolCluster = mysql.createPoolCluster(); // add configurations (the config is a pool config object) poolCluster.add(config); // add configuration with automatic name poolCluster.add('MASTER', masterConfig); // add a named configuration poolCluster.add('SLAVE1', slave1Config); poolCluster.add('SLAVE2', slave2Config); // remove configurations poolCluster.remove('SLAVE2'); // By nodeId poolCluster.remove('SLAVE*'); // By target group : SLAVE1-2 // Target Group : ALL(anonymous, MASTER, SLAVE1-2), Selector : round-robin(default) poolCluster.getConnection(function (err, connection) {}); // Target Group : MASTER, Selector : round-robin poolCluster.getConnection('MASTER', function (err, connection) {}); // Target Group : SLAVE1-2, Selector : order // If can't connect to SLAVE1, return SLAVE2. (remove SLAVE1 in the cluster) poolCluster.on('remove', function (nodeId) { console.log('REMOVED NODE : ' + nodeId); // nodeId = SLAVE1 }); // A pattern can be passed with * as wildcard poolCluster.getConnection('SLAVE*', 'ORDER', function (err, connection) {}); // The pattern can also be a regular expression poolCluster.getConnection(/^SLAVE[12]$/, function (err, connection) {}); // of namespace : of(pattern, selector) poolCluster.of('*').getConnection(function (err, connection) {}); var pool = poolCluster.of('SLAVE*', 'RANDOM'); pool.getConnection(function (err, connection) {}); pool.getConnection(function (err, connection) {}); pool.query(function (error, results, fields) {}); // close all connections poolCluster.end(function (err) { // all connections in the pool cluster have ended }); ``` -------------------------------- ### Implicitly Establishing MySQL Connection via Query (Node.js) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Shows an alternative method for establishing a MySQL connection where the connection is implicitly opened when the first query is executed. It uses `mysql.createConnection` for configuration and then calls `connection.query` directly. Note that error handling for the query itself is shown, but connection errors are fatal and handled separately. ```JavaScript var mysql = require('mysql'); var connection = mysql.createConnection(...); connection.query('SELECT 1', function (error, results, fields) { if (error) throw error; // connected! }); ``` -------------------------------- ### Running Unit Tests with npm Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Executes the unit test suite for the project. It uses the `npm test` command and sets the `FILTER` environment variable to `unit` to specifically target unit tests. This command does not require a running MySQL server. ```sh $ FILTER=unit npm test ``` -------------------------------- ### Preparing SQL Query String with mysql.format Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Shows how to use `mysql.format` to prepare a complete SQL query string by replacing `??` (identifiers) and `?` (values) placeholders with their properly escaped counterparts from an array of values. ```js var sql = "SELECT * FROM ?? WHERE ?? = ?"; var inserts = ['users', 'id', userId]; sql = mysql.format(sql, inserts); ``` -------------------------------- ### Creating MySQL Connection using URL String - JavaScript Source: https://github.com/mysqljs/mysql/blob/master/Readme.md This snippet demonstrates how to create a MySQL database connection using a connection URL string instead of passing an options object. The URL string includes parameters such as user, password, host, database, debug flag, charset, and timezone. ```javascript var connection = mysql.createConnection('mysql://user:pass@host/db?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700'); ``` -------------------------------- ### Handling MySQL Pool 'release' Event - Node.js Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Shows how to listen for the 'release' event, which is emitted when a connection is returned to the pool after being used. This occurs after all release-related activities are complete. ```js pool.on('release', function (connection) { console.log('Connection %d released', connection.threadId); }); ``` -------------------------------- ### Executing a Transaction in node-mysql (JS) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Illustrates how to perform a transaction using `connection.beginTransaction`, `connection.query`, `connection.commit`, and `connection.rollback`. It shows how to handle errors at each step by rolling back the transaction. Requires an active `node-mysql` connection. ```javascript connection.beginTransaction(function(err) {\n if (err) { throw err; }\n connection.query('INSERT INTO posts SET title=?', title, function (error, results, fields) {\n if (error) {\n return connection.rollback(function() {\n throw error;\n });\n }\n\n var log = 'Post ' + results.insertId + ' added';\n\n connection.query('INSERT INTO log SET data=?', log, function (error, results, fields) {\n if (error) {\n return connection.rollback(function() {\n throw error;\n });\n }\n connection.commit(function(err) {\n if (err) {\n return connection.rollback(function() {\n throw err;\n });\n }\n console.log('success!');\n });\n });\n });\n}); ``` -------------------------------- ### Handling MySQL Pool 'acquire' Event - Node.js Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Shows how to listen for the 'acquire' event emitted by the connection pool. This event fires just before a connection is handed to the code that requested it, indicating a connection has been successfully acquired from the pool. ```js pool.on('acquire', function (connection) { console.log('Connection %d acquired', connection.threadId); }); ``` -------------------------------- ### Performing Parameterized SQL Query with mysqljs/mysql (JS) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Shows how to use placeholders (?) in the SQL string and provide values as an array in the second argument. This is the recommended way to prevent SQL injection. The callback receives error, results, and fields. ```js 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) }); ``` -------------------------------- ### Connecting with Custom CA - mysql - JavaScript Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Demonstrates how to establish a MySQL connection using SSL by providing a custom Certificate Authority (CA) certificate. The `ca` option within the `ssl` object is used to specify the trusted certificate content, typically read from a file. ```JavaScript var connection = mysql.createConnection({ host : 'localhost', ssl : { ca : fs.readFileSync(__dirname + '/mysql-ca.crt') } }); ``` -------------------------------- ### Pinging the Server in node-mysql (JS) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Demonstrates how to use the `connection.ping` method to send a ping to the connected MySQL server. The callback is executed upon receiving a response or if an error occurs, indicating the server's reachability. Requires an active `node-mysql` connection. ```javascript connection.ping(function (err) {\n if (err) throw err;\n console.log('Server responded to ping');\n}) ``` -------------------------------- ### Handling Fatal Errors with Multiple Callbacks (JavaScript) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Demonstrates how fatal errors, such as connection refusal, are propagated to all pending callbacks associated with a connection object. Both the `connect` and `query` callbacks receive the same fatal error object. ```js var connection = require('mysql').createConnection({ port: 1 // example blocked port }); connection.connect(function(err) { console.log(err.code); // 'ECONNREFUSED' console.log(err.fatal); // true }); connection.query('SELECT 1', function (error, results, fields) { console.log(error.code); // 'ECONNREFUSED' console.log(error.fatal); // true }); ``` -------------------------------- ### Performing SQL Query with Options Object in mysqljs/mysql (JS) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Illustrates executing a query using an options object as the first argument. This allows specifying parameters like `sql`, `timeout`, and `values`. The callback structure remains the same. ```js connection.query({ sql: 'SELECT * FROM `books` WHERE `author` = ?', timeout: 40000, // 40s values: ['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) }); ``` -------------------------------- ### Using toSqlString Method for Raw SQL - Node.js/MySQL Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Shows how to define an object with a `toSqlString` method. When this object is used as a value for a `?` placeholder, the method is called, and its return value is inserted directly into the SQL string without further escaping, useful for database functions. ```javascript var CURRENT_TIMESTAMP = { toSqlString: function() { return 'CURRENT_TIMESTAMP()'; } }; var sql = mysql.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]); console.log(sql); // UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42 ``` -------------------------------- ### Enabling Full Debug Mode in mysqljs (Node.js) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Creates a mysql connection with the `debug` option set to `true`. This configuration enables the logging of all incoming and outgoing packets to standard output, which is useful for troubleshooting connection issues. Requires the `mysql` library. ```js var connection = mysql.createConnection({debug: true}); ``` -------------------------------- ### Handling Normal Errors with Specific Callbacks (JavaScript) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Illustrates how non-fatal errors, like using a non-existent database, are only delivered to the specific callback associated with the failed operation. Subsequent operations with their own callbacks proceed normally. ```js connection.query('USE name_of_db_that_does_not_exist', function (error, results, fields) { console.log(error.code); // 'ER_BAD_DB_ERROR' }); connection.query('SELECT 1', function (error, results, fields) { console.log(error); // null console.log(results.length); // 1 }); ``` -------------------------------- ### Escaping Multiple Values with Placeholders - Node.js/MySQL Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Shows how to use multiple `?` placeholders in a query string. The values provided in the array argument are mapped to the placeholders in order, allowing the library to escape each value automatically before execution. ```javascript connection.query('UPDATE users SET foo = ?, bar = ?, baz = ? WHERE id = ?', ['a', 'b', 'c', userId], function (error, results, fields) { if (error) throw error; // ... }); ``` -------------------------------- ### Using mysql.raw() for Raw SQL - Node.js/MySQL Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Explains how `mysql.raw()` creates a special object that, when used as a value for a `?` placeholder, inserts the provided string directly into the SQL query without escaping. This is a convenient way to include raw SQL functions or expressions. ```javascript var CURRENT_TIMESTAMP = mysql.raw('CURRENT_TIMESTAMP()'); var sql = mysql.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]); console.log(sql); // UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42 ``` -------------------------------- ### Handling MySQL Pool 'enqueue' Event - Node.js Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Explains how to listen for the 'enqueue' event. This event is emitted when a request for a connection is queued because the pool has reached its `connectionLimit` and `waitForConnections` is true. ```js pool.on('enqueue', function () { console.log('Waiting for available connection slot'); }); ``` -------------------------------- ### Enabling Multiple Statements (mysqljs) - JavaScript Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Demonstrates how to configure a connection to allow executing multiple SQL statements separated by semicolons in a single query string. This feature is disabled by default for security reasons and must be explicitly enabled during connection creation. ```javascript var connection = mysql.createConnection({multipleStatements: true}); ``` -------------------------------- ### Streaming Query Results with Events (mysqljs) - JavaScript Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Shows how to process large query results row by row using event listeners on the query object. Explains handling errors, fields, individual rows, and the end of the stream. Highlights the use of `connection.pause()` and `connection.resume()` for flow control, especially when processing involves I/O. ```javascript var query = connection.query('SELECT * FROM posts'); query .on('error', function(err) { // Handle error, an 'end' event will be emitted after this as well }) .on('fields', function(fields) { // the field packets for the rows to follow }) .on('result', function(row) { // Pausing the connnection is useful if your processing involves I/O connection.pause(); processRow(row, function() { connection.resume(); }); }) .on('end', function() { // all rows have been received }); ``` -------------------------------- ### Setting Connection Flags - mysql (Node.js) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Configure connection flags using the `flags` option in `mysql.createConnection`. Provide a comma-separated string to add or remove default flags, using a minus sign (-) prefix to disable a default flag. ```javascript var connection = mysql.createConnection({ // disable FOUND_ROWS flag, enable IGNORE_SPACE flag flags: '-FOUND_ROWS,IGNORE_SPACE' }); ``` -------------------------------- ### Using ?? Placeholders for Identifier Escaping in mysql.query Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Explains and demonstrates using `??` as placeholders within the query string passed to `connection.query`. The corresponding values in the array will be automatically escaped as identifiers. ```js var userId = 1; var columns = ['username', 'email']; var query = connection.query('SELECT ?? FROM ?? WHERE id = ?', [columns, 'users', userId], function (error, results, fields) { if (error) throw error; // ... }); console.log(query.sql); // SELECT `username`, `email` FROM `users` WHERE id = 1 ``` -------------------------------- ### Changing MySQL Connection User/State (Node.js) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Demonstrates how to use the `changeUser` method on an active connection to switch the authenticated user and potentially modify other connection attributes like password, charset, or database. This operation resets connection state such as variables and transactions. An optional callback is used to handle the result. ```javascript connection.changeUser({user : 'john'}, function(err) { if (err) throw err; }); ``` -------------------------------- ### Inserting/Updating with Object and SET ? - Node.js/MySQL Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Explains how to pass a JavaScript object as the value for a `SET ?` placeholder. The library automatically converts the object's properties into `key = 'value'` pairs, escaping each value, for use in `INSERT` or `UPDATE` statements. ```javascript var post = {id: 1, title: 'Hello MySQL'}; var query = connection.query('INSERT INTO posts SET ?', post, function (error, results, fields) { if (error) throw error; // Neat! }); console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL' ``` -------------------------------- ### Performing SQL Query with Options and Separate Values in mysqljs/mysql (JS) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Shows a variation where query options are passed as the first argument and placeholder values as a separate array in the second argument. The values provided separately override values in the options object. The callback handles error, results, and fields. ```js connection.query({ sql: 'SELECT * FROM `books` WHERE `author` = ?', timeout: 40000, // 40s }, ['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) } ); ``` -------------------------------- ### Performing SQL Query with Single Non-Array Value in mysqljs/mysql (JS) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Describes a special case where if there is only one placeholder (?) and the value is not null, undefined, or an array, it can be passed directly as the second argument to `.query()`. The callback provides error, results, and fields. ```js 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) } ); ``` -------------------------------- ### Piping Query Results with Streams (mysqljs) - JavaScript Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Illustrates using the `.stream()` method on a query object to obtain a Node.js Readable Stream. This stream can be piped to other streams, providing automatic pause/resume based on downstream congestion and the `highWaterMark` option. Notes that the stream is in `objectMode`. ```javascript connection.query('SELECT * FROM posts') .stream({highWaterMark: 5}) .pipe(...); ``` -------------------------------- ### Streaming Multiple Statement Results (mysqljs) - JavaScript Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Demonstrates how to stream results from a query containing multiple statements using event listeners (`fields`, `result`). Notes that the event handlers receive an `index` parameter indicating which statement the result or fields belong to. Mentions that this interface is experimental. ```javascript var query = connection.query('SELECT 1; SELECT 2'); query .on('fields', function(fields, index) { // the fields for the result rows that follow }) .on('result', function(row, index) { // index refers to the statement this result belongs to (starts at 0) }); ``` -------------------------------- ### Querying with Separated Table/Column Names in node-mysql (JS) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Shows how to use the `nestTables` option with a string separator (e.g., `'_'`) to merge join results while avoiding column name collisions. Column names are prefixed with the table name and the separator (e.g., `table1_fieldA`). Requires an active `node-mysql` connection. ```javascript var options = {sql: '...', nestTables: '_'};\nconnection.query(options, function (error, results, fields) {\n if (error) throw error;\n /* results will be an array like this now:\n [{\n table1_fieldA: '...',\n table1_fieldB: '...',\n table2_fieldA: '...',\n table2_fieldB: '...',\n }, ...]\n */\n}); ``` -------------------------------- ### Escaping Single Value with Placeholder - Node.js/MySQL Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Illustrates using a `?` placeholder in the SQL query string and providing the value in an array as the second argument to `connection.query()`. The library automatically escapes the value and substitutes it into the query string. ```javascript connection.query('SELECT * FROM users WHERE id = ?', [userId], function (error, results, fields) { if (error) throw error; // ... }); ``` -------------------------------- ### Handling Errors via Connection 'error' Event (JavaScript) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Shows how errors are emitted as an 'error' event on the connection object if a fatal error occurs with no pending callbacks, or if a normal error occurs without a specific callback. Note that unhandled 'error' events can crash the Node.js process. ```js connection.on('error', function(err) { console.log(err.code); // 'ER_BAD_DB_ERROR' }); connection.query('USE name_of_db_that_does_not_exist'); ``` -------------------------------- ### Gracefully Ending Connection - mysql (Node.js) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Use the `end()` method to gracefully terminate a MySQL connection. This method ensures all previously enqueued queries are executed before sending a `COM_QUIT` packet to the server. An optional callback can be provided to handle completion. ```javascript connection.end(function(err) { // The connection is terminated now }); ``` -------------------------------- ### Setting a Query Timeout in node-mysql (JS) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Shows how to apply an inactivity timeout to a query using the `timeout` option in the query options object. If the operation exceeds the specified time (in milliseconds), the connection is destroyed, and an error with code `PROTOCOL_SEQUENCE_TIMEOUT` is thrown. Requires an active `node-mysql` connection. ```javascript // Kill query after 60s\nconnection.query({sql: 'SELECT COUNT(*) AS count FROM big_table', timeout: 60000}, function (error, results, fields) {\n if (error && error.code === 'PROTOCOL_SEQUENCE_TIMEOUT') {\n throw new Error('too long to count table rows!');\n }\n\n if (error) {\n throw error;\n }\n\n console.log(results[0].count + ' rows');\n}); ``` -------------------------------- ### Querying with Nested Tables in node-mysql (JS) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Demonstrates how to use the `nestTables: true` option in `connection.query` to structure join results with overlapping column names. Results are nested under their respective table names, preventing data loss from column name collisions. Requires an active `node-mysql` connection. ```javascript var options = {sql: '...', nestTables: true};\nconnection.query(options, function (error, results, fields) {\n if (error) throw error;\n /* results will be an array like this now:\n [{\n table1: {\n fieldA: '...',\n fieldB: '...',\n },\n table2: {\n fieldA: '...',\n fieldB: '...',\n },\n }, ...]\n */\n}); ``` -------------------------------- ### Ending MySQL Pool Connections (Node.js) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Demonstrates how to gracefully close all active connections within a MySQL connection pool using the `end` method. This is crucial for allowing the Node.js event loop to exit cleanly. An optional callback function can be provided to execute code once all connections have been terminated. ```javascript pool.end(function (err) { // all connections in the pool have ended }); ``` -------------------------------- ### Escaping Value with mysql.escape() - Node.js/MySQL Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Shows how to use the static `mysql.escape()` method to escape a single value. The escaped value can then be manually concatenated into a SQL query string. This is useful when building query strings piece by piece. ```javascript var query = "SELECT * FROM posts WHERE title=" + mysql.escape("Hello MySQL"); console.log(query); // SELECT * FROM posts WHERE title='Hello MySQL' ``` -------------------------------- ### Disabling Certificate Verification - mysql - JavaScript Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Illustrates how to disable server certificate verification by setting the `rejectUnauthorized` option to `false` within the `ssl` configuration. This is strongly discouraged for security reasons and should be avoided in production environments. ```JavaScript var connection = mysql.createConnection({ host : 'localhost', ssl : { // DO NOT DO THIS // set up your ca correctly to trust the connection rejectUnauthorized: false } }); ``` -------------------------------- ### Immediately Destroying Connection - mysql (Node.js) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Call the `destroy()` method to immediately terminate the underlying socket of a MySQL connection. This method guarantees that no more events or callbacks will be triggered for the connection, unlike the `end()` method. ```javascript connection.destroy(); ``` -------------------------------- ### Escaping Qualified SQL Identifier with mysql.escapeId Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Shows how `connection.escapeId` automatically handles and escapes qualified identifiers (e.g., `table.column`) when the second argument is not set to `true`. ```js var sorter = 'date'; var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId('posts.' + sorter); // -> SELECT * FROM posts ORDER BY `posts`.`date` ``` -------------------------------- ### Escaping SQL Identifier with mysql.escapeId (Basic) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Demonstrates using `connection.escapeId` to safely escape a single SQL identifier (like a column or table name) provided by a user to prevent SQL injection. ```js var sorter = 'date'; var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId(sorter); connection.query(sql, function (error, results, fields) { if (error) throw error; // ... }); ``` -------------------------------- ### Escaping Single Value with connection.escape() - Node.js/MySQL Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Shows how to manually escape a user-provided value using `connection.escape()` and concatenate it into the SQL query string before executing the query. This prevents SQL injection for the specific value. ```javascript var userId = 'some user provided value'; var sql = 'SELECT * FROM users WHERE id = ' + connection.escape(userId); connection.query(sql, function (error, results, fields) { if (error) throw error; // ... }); ``` -------------------------------- ### Enabling Restricted Debug Mode in mysqljs (Node.js) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Creates a mysql connection with the `debug` option set to an array of packet type names. This restricts the debugging output to only the specified packet types, such as `ComQueryPacket` and `RowDataPacket`, providing more focused logging. Requires the `mysql` library. ```js var connection = mysql.createConnection({debug: ['ComQueryPacket', 'RowDataPacket']}); ``` -------------------------------- ### Escaping Literal SQL Identifier with mysql.escapeId Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Illustrates using the second argument of `connection.escapeId` set to `true` to treat the input string as a single literal identifier, preventing the splitting and escaping of parts separated by a dot. ```js var sorter = 'date.2'; var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId(sorter, true); // -> SELECT * FROM posts ORDER BY `date.2` ``` -------------------------------- ### Disabling Type Casting at Query Level (JavaScript) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Shows how to disable type casting for an individual query by including the `typeCast: false` option within the options object passed to the `connection.query()` method. ```js var options = {sql: '...', typeCast: false}; var query = connection.query(options, function (error, results, fields) { if (error) throw error; // ... }); ``` -------------------------------- ### Disabling Type Casting at Connection Level (JavaScript) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Demonstrates how to disable the default type casting behavior for all queries executed on a specific connection by setting the `typeCast` option to `false` during connection creation. ```js var connection = require('mysql').createConnection({typeCast: false}); ``` -------------------------------- ### Custom Type Casting for TINYINT(1) in mysqljs (Node.js) Source: https://github.com/mysqljs/mysql/blob/master/Readme.md Configures a mysql connection to use a custom type casting function. This function checks if the field is a `TINYINT(1)` and converts its string value ('1' or '0') to a boolean (`true` or `false`), otherwise it uses the default type casting provided by the `next` function. Requires the `mysql` library. ```js connection = mysql.createConnection({ typeCast: function (field, next) { if (field.type === 'TINY' && field.length === 1) { return (field.string() === '1'); // 1 = true, 0 = false } else { return next(); } } }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.