H5連接MySQL的方法
1. 連接MySQL:
let mysql = require('mysql'); let connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '123456', port: '3306', database: 'test' }); connection.connect();
2. 查詢數據:
let querySql = 'SELECT * FROM user'; connection.query(querySql, function (err, results, fields) { if (err) throw err; console.log(results); });
3. 插入數據:
let addSql = 'INSERT INTO user(username, password) VALUES(?,?)'; let addSqlParams = ['user1', '123456']; connection.query(addSql, addSqlParams, function (err, results, fields) { if (err) throw err; console.log(results); });
4. 更新數據:
let updateSql = 'UPDATE user SET password=? WHERE username=?'; let updateSqlParams = ['654321', 'user1']; connection.query(updateSql, updateSqlParams, function (err, results, fields) { if (err) throw err; console.log(results); });
5. 刪除數據:
let deleteSql = 'DELETE FROM user WHERE username=?'; let deleteSqlParams = ['user1']; connection.query(deleteSql, deleteSqlParams, function (err, results, fields) { if (err) throw err; console.log(results); });
6. 斷開連接:
connection.end();
通過以上代碼,我們可以連接到MySQL數據庫,并進行數據的增刪改查操作。