This article introduces nodejs access to the mysql database.
The mysql database needs to be used in the project. The following describes how to access mysql
Here I am using mac for development, first download mysql
Address: http://dev.mysql.com/downloads/mysql/
Refer to this installation http://dev.mysql.com/doc/refman/5.0/en/macosx-installation.html
After the installation is complete, you can see mysql in the preference settings, through which you can start to close mysql.
After the installation is complete by default, the root user of the database does not have a password.
For ease of operation, I have installed sequelpro, a graphical mysql operating tool.
: Http://www.sequelpro.com/download/
The installation is successful and the logon interface is shown in:
After logging on as root, you can add a password to the root user.
The above is a brief introduction to mysql installation. The following describes how to use nodejs to access mysql.
Create an express project. Here I use db-mysql
Http://nodejsdb.org/db-mysql/
According to the above introduction
Before that, run the following command in the command line:
The Code is as follows: |
Copy code |
Export MYSQL_CONFIG =/usr/local/mysql/bin/mysql_config |
Then install db-mysql
The Code is as follows: |
Copy code |
Npm install db-mysql |
Then, write a js file. Here I refer to the official example and write a data read from the user table in the test database in mysql:
Code:
The Code is as follows: |
Copy code |
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 ); } }); }); |
It is very simple. Then I use this js, but there is a problem:
Throw e; // process. nextTick error, or 'error' event on first tick
^
Error: Unable to load shared library/Users/wanzhang/WebstormProjects/ReadMysql/node_modules/db-
The Code is as follows: |
Copy code |
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) |
Solution:
Export DYLD_LIBRARY_PATH =/usr/local/mysql/lib/
Then run the js file, OK, and the data in the table will be printed.
The above is a simple example of nodejs accessing mysql.