在Web开发中,数据库一直扮演着一个重要的角色。而MySQL作为最常用的关系型数据库管理系统,往往被利用在Web服务中。本文将介绍通过js直接写MySQL数据库。
//1.加载MySQL模块const mysql = require('mysql')//2.创建数据库连接const conn = mysql.createConnection({host: 'localhost',user: 'root',password: '123456',database: 'test'})//3.连接数据库conn.connect(err =>{if (err) {console.log('数据库连接失败')throw err}console.log('数据库连接成功')})//4.查询和读取数据const selectSql = `SELECT * FROM customers`conn.query(selectSql, (error, results, fields) =>{if (error) throw errorconsole.log(results)})//5.插入数据const insertSql = `INSERT INTO customers (name, email) VALUES ('John', 'john@example.com')`conn.query(insertSql, (error, results, fields) =>{if (error) throw errorconsole.log('数据插入成功')})//6.更新数据const updateSql = `UPDATE customers SET email='john@example.org' WHERE name='John'`conn.query(updateSql, (error, results, fields) =>{if (error) throw errorconsole.log('数据更新成功')})//7.删除数据const deleteSql = `DELETE FROM customers WHERE name='John'`conn.query(deleteSql, (error, results, fields) =>{if (error) throw errorconsole.log('数据删除成功')})//8.关闭数据库连接conn.end(err =>{if (err) {console.log('数据库关闭失败')throw err}console.log('数据库已关闭')})
以上代码将通过Node.js执行,在本地MySQL数据库中进行操作。其中,我们首先加载MySQL模块。创建数据库连接后,我们可以通过query方法实现查询、插入、更新、删除数据等操作,并且可以通过回调函数获取返回结果。最后,我们关闭数据库连接以结束操作。
需要注意的是,通过js直接操作MySQL存在一定的风险,如SQL注入等安全问题。因此,开发者需谨慎操作,并加强安全防护措施。