index.js

  1. const mysql = require("mysql");
  2. // 创建链接对象
  3. const con = mysql.createConnection({
  4. host: "localhost",
  5. user: "root",
  6. password: "wuchendi",
  7. port: "3306",
  8. database: "myblog",
  9. });
  10. // 开始连接
  11. con.connect();
  12. // 执行 sql 语句
  13. // const sql = "select * from users";
  14. // const sql = "select id, username from users";
  15. // const sql = `SELECT * FROM users WHERE state='1'`;
  16. // const sql = `UPDATE users set state='0' WHERE username='wcd'`;
  17. // const sql = `update users set realname='wuchendi3' where username = 'wcd1'`;
  18. const sql = `insert into blogs (title, content, createtime, author) values ('标题', '内容',1560818599043, 'wuchendi')`;
  19. con.query(sql, (err, result) => {
  20. if (err) {
  21. console.error(err);
  22. return;
  23. }
  24. console.log(result);
  25. });
  26. // 关闭连接
  27. con.end();

package.json

  1. {
  2. "name": "mysql-test",
  3. "version": "1.0.0",
  4. "description": "",
  5. "main": "index.js",
  6. "scripts": {
  7. "test": "echo \"Error: no test specified\" && exit 1"
  8. },
  9. "keywords": [],
  10. "author": "",
  11. "license": "ISC",
  12. "dependencies": {
  13. "mysql": "^2.16.0"
  14. }
  15. }