最近在搞nodejs,要作一些數據庫的相關操做,數據庫用的是Mysql,網上也有很多代碼,紅薯也一篇博文說明了相關操做,可是拿來用的時候,發現了一些小問題,仔細研究,紅薯提供的代碼是官方的舊代碼(你們有興趣的能夠搜索一下紅薯關於這個操做的介紹),也許是後續的nodejs mysql版本作了改動,以致於以前的代碼沒法編譯,這裏小弟就爲你們更新一下。node
首先是安裝nodejs有關mysql的包mysql
1 |
$npm install mysql |
鏈接代碼:web
01 |
//init the connection |
02 |
var Client = require( 'mysql' ).createConnection({ |
03 |
04 |
05 |
host: "127.0.0.1" , |
06 |
user: "root" , |
07 |
password: "root" , |
08 |
database: "test" |
09 |
10 |
11 |
}); |
12 |
13 |
14 |
console.log( 'Connecting to MySQL...' ); |
15 |
Client.connect( function (error, results) { |
16 |
if (error) { |
17 |
console.log( 'Connection Error: ' + error.message); |
18 |
return ; |
19 |
} |
20 |
console.log( 'Connected to MySQL successfully!' ); |
21 |
}); |
22 |
23 |
//select the DB |
24 |
Client.query( 'use test' , function (error, results) { |
25 |
if (error) { |
26 |
console.log( 'ClientConnectionReady Error: ' + error.message); |
27 |
// client.end(); |
28 |
return ; |
29 |
} |
30 |
}); |
31 |
//select sql statement |
32 |
Client.query( 'select * from eric' , function (error, results) { |
33 |
if (error) { |
34 |
console.log( 'ClientConnectionReady Error: ' + error.message); |
35 |
client.end(); |
36 |
return ; |
37 |
} |
38 |
console.log(results); |
39 |
}); //insert sql statement; |
40 |
/*Client.query('insert into eric values(3,"a")', function(error, results) { |
41 |
if(error) { |
42 |
console.log('ClientConnectionReady Error: ' + error.message); |
43 |
client.end(); |
44 |
return; |
45 |
} |
46 |
console.log("insert successfully!"); |
47 |
});*/ |
48 |
49 |
50 |
//delete sql statement |
51 |
/*Client.query('delete from eric where id=3', function(error, results) { |
52 |
if(error) { |
53 |
console.log('ClientConnectionReady Error: ' + error.message); |
54 |
client.end(); |
55 |
return; |
56 |
} |
57 |
console.log("delete successfully!"); |
58 |
});*/ |
59 |
//update sql statement |
60 |
Client.query( 'update eric set name="alice" where id=2' , function (error, results) { |
61 |
if (error) { |
62 |
console.log( 'ClientConnectionReady Error: ' + error.message); |
63 |
client.end(); |
64 |
return ; |
65 |
} |
66 |
console.log( "update successfully!" ); |
67 |
}); <span><span style= "line-height:20px;" > </span></span> |