初步使用Node串連Mysql資料庫_node.js

來源:互聯網
上載者:User

使用Node做Web頁面開發,基本上是串連非關係型資料庫mongodb,而這裡我還是先嘗試串連了一下mysql資料庫,因為相對於mysql來說mongodb過於生疏,想著快速出來頁面,所以選擇相對熟悉一些的mysql。

1. 安裝mysql

下載MySQL :MySQL Downloads,並進行安裝。安裝完,會引導你對資料庫進行配置,設定root密碼以及建立普通使用者以及密碼。

2. 安裝Node-mysql

通過npm安裝mysql的軟體包,通過它方便快速調用函數串連mysql資料庫。進入專案檔夾,執行npm install mysql --save就行了。

安裝完,在專案檔夾的node_modules目錄下會產生mysql的目錄。

3. 查看readme文檔

進入mysql目錄中,查看README文檔,這步很重要,不要到處百度Google搜尋怎麼用,因為由於版本的不一樣,也許你得到的答案並不能使你成功串連資料庫。畢竟Node發展如此之快。

如果你認真讀了README文檔,接下來的步驟就不用再看了,避免由於版本不一致而誤導你。

4. 串連mysql資料庫

進入項目文檔,建立TestMysql.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(err, rows, fields) { if (err) throw err; console.log('The solution is: ', rows[0].solution);});connection.end();

串連基本參數

  • host 主機名稱,localhost代表本地
  • user Mysql使用者
  • password 密碼
  • database 串連的資料庫

client.connect()串連資料庫

client.query()執行SQL語句
client.end()關閉串連。
然後通過node TestMysql.js執行程式,確保你在執行之前已經啟動了Mysql服務。

5. 增刪改查

使用資料庫無外乎增刪改查,下面樣本可能會對你有些協助。

var mysql   = require('mysql');var connection = mysql.createConnection({ host   : 'localhost', user   : 'me', password : 'secret', database : 'my_db'});connection.connect();// 增加記錄client.query('insert into test (username ,password) values ("lupeng" , "123456")');// 刪除記錄client.query('delete from test where username = "lupeng"');// 修改記錄client.query('update test set username = "pengloo53" where username = "lupeng"');// 查詢記錄client.query("select * from test" , function selectTable(err, rows, fields){ if (err){  throw err; } if (rows){  for(var i = 0 ; i < rows.length ; i++){   console.log("%d\t%s\t%s", rows[i].id,rows[i].username,rows[i].password);  } }});connection.end();

到此,Mysql資料庫的初步串連就告一段落了,接下來就可以在Node項目中自行發揮了。

希望大家繼續關注。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.