-
Notifications
You must be signed in to change notification settings - Fork 0
/
is_this_right_way_to_use_queries.js
45 lines (37 loc) · 1.11 KB
/
is_this_right_way_to_use_queries.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
To answer your questions,
For the example you provided, please take a look at transactions
var mysql = require('mysql');
var connection = mysql.createConnection({...});
// Open it up
connection.connect();
connection.beginTransaction(function(err){
if(err) { throw err; }
// for any values, make sure to use connection.escape() to sanitize user input
var insertQuery = 'Insert into table values(....)';
connection.query(insertQuery, function(err, result) {
if (err) {
return connection.rollback(function() {
throw err;
});
}
//get the auto incremented value from first insert and use it in the second insert
var rowId = result.insertId;
var insertQuery2 = "insert into table2 values(" + rowId + ",..)";
connection.query(insertQuery2, function(err, result){
if(err) {
return connection.rollback(function(){
throw err;
});
}
connection.commit(function(err){
if (err) {
return connection.rollback(function() {
throw err;
});
}
});
});
});
});
// Close it up
connection.end();