NodeJs与MySQL交互数据

末蓝、 2022-09-23 03:46 204阅读 0赞
  1. // mysqlTest.js
  2. //加载mysql Module
  3. var Client = require('mysql').Client,
  4. client = new Client(),
  5.   
  6.   //要创建的数据库名
  7. TEST_DATABASE = 'nodejs_mysql_test',
  8. //要创建的表名
  9. TEST_TABLE = 'test';
  10. //用户名
  11. client.user = 'root';
  12. //密码
  13. client.password = 'root';
  14. //创建连接
  15. client.connect();
  16. client.query('CREATE DATABASE '+TEST_DATABASE, function(err) {
  17. if (err && err.number != Client.ERROR_DB_CREATE_EXISTS) {
  18. throw err;
  19. }
  20. });
  21. // If no callback is provided, any errors will be emitted as `'error'`
  22. // events by the client
  23. client.query('USE '+TEST_DATABASE);
  24. client.query(
  25. 'CREATE TABLE '+TEST_TABLE+
  26. '(id INT(11) AUTO_INCREMENT, '+
  27. 'title VARCHAR(255), '+
  28. 'text TEXT, '+
  29. 'created DATETIME, '+
  30. 'PRIMARY KEY (id))'
  31. );
  32. client.query(
  33. 'INSERT INTO '+TEST_TABLE+' '+
  34. 'SET title = ?, text = ?, created = ?',
  35. ['super cool', 'this is a nice text', '2010-08-16 10:00:23']
  36. );
  37. var query = client.query(
  38. 'INSERT INTO '+TEST_TABLE+' '+
  39. 'SET title = ?, text = ?, created = ?',
  40. ['another entry', 'because 2 entries make a better test', '2010-08-16 12:42:15']
  41. );
  42. client.query(
  43. 'SELECT * FROM '+TEST_TABLE,
  44. function selectCb(err, results, fields) {
  45. if (err) {
  46. throw err;
  47. }
  48. console.log(results);
  49. console.log(fields);
  50. client.end();
  51. });

欢迎加入node.js交流群:572416249

发表评论

表情:
评论列表 (有 0 条评论,204人围观)

还没有评论,来说两句吧...

相关阅读

    相关 mysqlpython交互

    与python交互 在熟练使用sql语句的基础上,开始使用python语言提供的模块与mysql进行交互 这是我们在工作中大事要做的事 先学会sql是基