You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
connection.connect(function(err) { // The server is either down
378
+
if(err) { // or restarting (takes a while sometimes).
379
+
console.log('error when connecting to db:', err);
380
+
setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
381
+
} // to avoid a hot loop, and to allow our node script to
382
+
}); // process asynchronous requests in the meantime.
383
+
// If you're also serving http, display a 503 error.
384
+
connection.on('error', function(err) {
385
+
console.log('db error', err);
386
+
if(err.code==='PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
387
+
handleDisconnect(); // lost due to either server restart, or a
388
+
} else { // connnection idle timeout (the wait_timeout
389
+
throw err; // server variable configures this)
390
+
}
323
391
});
324
392
}
325
393
326
-
handleDisconnect(connection);
394
+
handleDisconnect();
327
395
```
328
396
329
397
As you can see in the example above, re-connecting a connection is done by
@@ -337,7 +405,7 @@ space for a new connection to be created on the next getConnection call.
337
405
338
406
In order to avoid SQL Injection attacks, you should always escape any user
339
407
provided data before using it inside a SQL query. You can do so using the
340
-
`connection.escape()`method:
408
+
`connection.escape()`or `pool.escape()` methods:
341
409
342
410
```js
343
411
var userId ='some user provided value';
@@ -430,6 +498,18 @@ connection.query('SELECT * FROM ?? WHERE id = ?', ['users', userId], function(er
430
498
431
499
When you pass an Object to `.escape()` or `.query()`, `.escapeId()` is used to avoid SQL injection in object keys.
432
500
501
+
### Preparing Queries
502
+
503
+
You can use mysql.format to prepare a query with multiple insertion points, utilizing the proper escaping for ids and values. A simple example of this follows:
504
+
505
+
```js
506
+
var sql ="SELECT * FROM ?? WHERE ?? = ?";
507
+
var inserts = ['users', 'id', userId];
508
+
sql =mysql.format(sql, inserts);
509
+
```
510
+
511
+
Following this you then have a valid, escaped query that you can then send to the database safely. This is useful if you are looking to prepare the query before actually sending it to the database. As mysql.format is exposed from SqlString.format you also have the option (but are not required) to pass in stringifyObject and timezone, allowing you provide a custom means of turning objects into strings, as well as a location-specific/timezone-aware Date.
512
+
433
513
### Custom format
434
514
435
515
If you prefer to have another type of query escape format, there's a connection configuration option you can use to define a custom format function. You can access the connection object if you want to use the built-in `.escape()` or any other connection function.
Simple transaction support is available at the connection level:
719
+
720
+
```js
721
+
connection.beginTransaction(function(err) {
722
+
if (err) { throw err; }
723
+
connection.query('INSERT INTO posts SET title=?', title, function(err, result) {
724
+
if (err) {
725
+
connection.rollback(function() {
726
+
throw err;
727
+
});
728
+
}
729
+
730
+
var log ='Post '+result.insertId+' added';
731
+
732
+
connection.query('INSERT INTO log SET data=?', log, function(err, result) {
733
+
if (err) {
734
+
connection.rollback(function() {
735
+
throw err;
736
+
});
737
+
}
738
+
connection.commit(function(err) {
739
+
if (err) {
740
+
connection.rollback(function() {
741
+
throw err;
742
+
});
743
+
}
744
+
console.log('success!');
745
+
});
746
+
});
747
+
});
748
+
});
749
+
```
750
+
Please note that beginTransaction(), commit() and rollback() are simply convenience
751
+
functions that execute the START TRANSACTION, COMMIT, and ROLLBACK commands respectively.
752
+
It is important to understand that many commands in MySQL can cause an implicit commit,
753
+
as described [in the MySQL documentation](http://dev.mysql.com/doc/refman/5.5/en/implicit-commit.html)
754
+
636
755
## Error handling
637
756
638
757
This module comes with a consistent approach to error handling that you should
@@ -775,7 +894,7 @@ Or on the query level:
775
894
var options = {sql:'...', typeCast:false};
776
895
var query =connection.query(options, function(err, results) {
777
896
778
-
}):
897
+
});
779
898
```
780
899
781
900
You can also pass a function and handle type casting yourself. You're given some
@@ -792,11 +911,23 @@ connection.query({
792
911
}
793
912
returnnext();
794
913
}
795
-
})
914
+
});
915
+
```
916
+
__WARNING: YOU MUST INVOKE the parser using one of these three field functions in your custom typeCast callback. They can only be called once.( see #539 for discussion)__
917
+
918
+
```
919
+
field.string()
920
+
field.buffer()
921
+
field.geometry()
922
+
```
923
+
are aliases for
924
+
```
925
+
parser.parseLengthCodedString()
926
+
parser.parseLengthCodedBuffer()
927
+
parser.parseGeometryValue()
796
928
```
929
+
__You can find which field function you need to use by looking at: [RowDataPacket.prototype._typeCast](https://github.com/felixge/node-mysql/blob/master/lib/protocol/packets/RowDataPacket.js#L41)__
797
930
798
-
If you need a buffer there's also a `.buffer()` function and also a `.geometry()` one
799
-
both used by the default type cast that you can use.
800
931
801
932
## Connection Flags
802
933
@@ -813,7 +944,7 @@ prepend the flag with a minus sign. To add a flag that is not in the default lis
813
944
The next example blacklists FOUND_ROWS flag from default connection flags.
814
945
815
946
```js
816
-
var connection =mysql.createConnection("mysql://localhost/test?flags=-FOUND_ROWS")
947
+
var connection =mysql.createConnection("mysql://localhost/test?flags=-FOUND_ROWS");
817
948
```
818
949
819
950
### Default Flags
@@ -886,11 +1017,10 @@ For example, if you have an installation of mysql running on localhost:3306 and
886
1017
* Make sure the database (e.g. 'test') you want to use exists and the user you entered has the proper rights to use the test database. (E.g. do not forget to execute the SQL-command ```FLUSH PRIVILEGES``` after you have created the user.)
887
1018
* In a DOS-box (or CMD-shell) in the folder of your application run ```npm install mysql --dev``` or in the mysql folder (```node_modules\mysql```), run ```npm install --dev```. (This will install additional developer-dependencies for node-mysql.)
888
1019
* Run ```npm test mysql``` in your applications folder or ```npm test``` in the mysql subfolder.
889
-
* If you want to log the output into a file use ```npm test mysql > test.log``` or ```npm test > test.log```.
1020
+
* If you want to log the output into a file use ```npm test mysql > test.log``` or ```npm test > test.log```.
890
1021
891
1022
## Todo
892
1023
893
1024
* Prepared statements
894
1025
* setTimeout() for Connection / Query
895
-
* Support for encodings other than UTF-8 / ASCII
896
-
* API support for transactions, similar to [php](http://www.php.net/manual/en/mysqli.quickstart.transactions.php)
0 commit comments