# 二.学生成绩表增删改查

# 1.启动mysql

这里直接以桌面版 docker 为例,直接启动

# 2.安装依赖

npm i mysql -S
1

# 3.使用mysql

  • 这里后端以 node 为例子

/mysql.js

const mysql = require("mysql")
let { MONGO_URL, MYSQL_URL, MYSQL_PORT, _AUTHSOURCE, MYSQL_USER, MYSQL_PASS, LOCAL } = process.env;
console.log(MYSQL_URL, MYSQL_PORT, MYSQL_USER, MYSQL_PASS)
const connection = mysql.createConnection({
    host: MYSQL_URL,
    port: MYSQL_PORT,
    user: MYSQL_USER,
    password: MYSQL_PASS,
    database: "common_node_student",
    insecureAuth:true
})
connection.connect()
function sql_add(s_name, s_english, s_math, callback) {
    let userAddSql = "INSERT INTO student(s_name,s_english,s_math) VALUES(?,?,?)"
    let userAddSql_params = [s_name, s_english, s_math]
    connection.query(userAddSql, userAddSql_params, function (err, result) {
        if (err) {
            console.log(err)
        } else {
            callback && callback(result)
            console.log("增加", JSON.stringify(result))
        }
    })
}
function sql_delete(id, callback) {
    let userDeleteSql = `DELETE FROM student WHERE id=${id}`
    connection.query(userDeleteSql, function (err, result) {
        callback && callback(result)
        console.log("删除", JSON.stringify(result))
    })
}
function sql_update(id, s_name, s_english, s_math, callback) {
    console.log(typeof s_name)
    let userChangeSql = `UPDATE student SET s_name="${s_name}",s_english=${s_english},s_math=${s_math} WHERE id=${id}`
    connection.query(userChangeSql, function (err, result) {
        if (err) {
            console.log(err)
        } else {
            callback && callback(result)
            console.log("修改", JSON.stringify(result))
        }
    })
}
function sql_query(callback) {
    let userSearchSql = "SELECT * FROM student"
    connection.query(userSearchSql, function (err, result) {
        if (err) {
            console.log("查找失败", err)
        } else {
            console.log("查找", JSON.stringify(result))
            callback && callback(result)
        }
    })
}
module.exports = {
    sql_add,
    sql_delete,
    sql_update,
    sql_query,
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

# 4.实现增删改查

# 5.可视化