关于node.js与MySQL交互

来源:互联网 发布:富士施乐驱动for mac 编辑:程序博客网 时间:2024/06/07 01:55

这个走过很多弯路。。。特此做个笔记~
错误包括:

  • 没有安装MySQL就连接,服务里找不到MySQL
  • cmd命令行安装MySQL时,没有以管理员身份运行
  • 安装MySQL成功后,没有启动MySQL服务

正确的操作顺序是:

  1. 在本地电脑上安装MySQL
  2. 在系统环境变量中配置路径,在PATH中配置MySQL安装目录下的bin文件夹路径
  3. 在MySQL安装目录下新建一个my.ini文件,自己配置好(百度)
  4. 以管理员身份打开cmd,切换到MySQL的bin文件目录下,执行mysqld -install,如果PATH变量已设置,则不需要切换路径
  5. 打开MySQL服务,执行net start mysql,或者手动启动MySQL服务
  6. 以管理员身份运行mysql -u root -p,初始密码没有,直接回车,连接成功
  7. 然后再在sublime或者Visual Studio Code中建立node连接MySQL的js文件(见附件),即可连接成功!
  8. 注意7中建立connection的信息:
    主机为host:127.0.0.1‘’,
    用户名为MySQL认证用户名user:‘root’,
    密码为MySQL认证用户密码(空)password:‘’,
    端口号为port:‘3306’,

终于成功了,感谢百度,感谢谷歌,感谢爸爸妈妈,感谢自己!

var mysql = require('mysql');  //调用MySQL模块//创建一个connectionvar connection = mysql.createConnection({host       : '127.0.0.1',    //主机user       : 'root',         //MySQL认证用户名password   : '',             //MySQL认证用户密码port       : '3306',         //端口号});//创建一个connectionconnection.connect(function(err) {if(err) {console.log('[query] - : ' + err);return;}console.log('[connection connect] succeed!');});//执行SQL语句connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {if(err) {console.log('[query] - : ' + err);return;}console.log('The solution is: ', rows[0].solution);});//关闭connectionconnection.end(function(err) {if(err) {return;}console.log('[connection end] succeed!');});