nodejs訪問mysql資料庫使用說明詳解

來源:互聯網
上載者:User

項目中需要使用mysql資料庫,下面就介紹下怎麼訪問mysql

這裡我使用的mac進行開發的,首先需要下載mysql

地址:http://dev.mysql.com/downloads/mysql/

參考這篇安裝http://dev.mysql.com/doc/refman/5.0/en/macosx-installation.html

安裝完成後可以在喜好設定裡面看到mysql,通過這個可以啟動關閉mysql。

預設安裝完成後,資料庫的root使用者是沒有密碼的。

為了方便操作,這裡我又安裝了一個mysql的圖形化操作工具sequelpro
下載地址:http://www.sequelpro.com/download/

安裝成功並且登陸後的介面如下圖所示:

 

以root登入後可以給root使用者加上密碼。

上面是對mysql安裝進行了簡單的介紹。下面介紹下怎樣使用nodejs訪問mysql

建立express項目,這裡我使用的db-mysql

官方網址:http://nodejsdb.org/db-mysql/

根據它上面的介紹

在這之前需要在命令列中運行下面這個命令:

 代碼如下 複製代碼

export MYSQL_CONFIG=/usr/local/mysql/bin/mysql_config

然後安裝db-mysql

 代碼如下 複製代碼

npm install db-mysql

然後編寫一個js檔案,這裡我參考官方例子,自己寫了一個讀取mysql中的test資料庫中user表中的資料:

代碼:

 代碼如下 複製代碼

var mysql = require(‘db-mysql’);
new mysql.Database({
hostname: ‘localhost’,
user: ‘root’,
password: ‘password’,
database: ‘test’
}).connect(function(error) {
if (error) {
return console.log(‘CONNECTION error: ‘ + error);
}
this.query().
select(‘*’).
from(‘user’).
execute(function(error, rows, cols) {
if (error) {
console.log(‘ERROR: ‘ + error);
return;
}
for(var i=0;i<rows.length;i++){
console.log(rows[i].name );
}

});
});

很簡單,然後我用行這個js,但是出現了問題:

        throw e; // process.nextTick error, or ‘error’ event on first tick
^
Error: Unable to load shared library /Users/wanzhang/WebstormProjects/ReadMysql/node_modules/db-

 代碼如下 複製代碼
mysql/build/Release/mysql_bindings.node
at Object..node (module.js:472:11)
at Module.load (module.js:348:31)
at Function._load (module.js:308:12)
at Module.require (module.js:354:17)
at require (module.js:370:17)
at Object.<anonymous> (/Users/wanzhang/WebstormProjects/ReadMysql/node_modules/db-mysql/db-mysql.js:18:15)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:31)
at Function._load (module.js:308:12)


解決方案:

export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/

然後再運行這個js檔案,ok,會列印出表中資料。

上面就是nodejs訪問mysql一個簡單例子。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.