使用Golang更新MySQL数据库时遇到的问题

使用Golang更新MySQL数据库时遇到的问题 大家好,

我一直在使用一个教程(http://www.golangprograms.com/advance-programs/example-of-golang-crud-using-mysql-from-scratch.html) 已经成功创建了应用程序。我能够更新员工信息,但无法通过网页界面创建新员工。 代码中是否存在错误?我找不到问题所在。

12 回复

干得漂亮!

更多关于使用Golang更新MySQL数据库时遇到的问题的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


我以root权限运行…… 完全照搬了我提到的网站上的代码……

你在索引页面上看到变化了吗?如何查看 MySQL 中的表格,使用 MySQL Workbench?

我想我找到了解决方法。我为新条目添加了Id列 在模板和主文件夹中都进行了添加。现在我已经能够添加新的人员了。

你说得对 我重新检查后发现MySQL中的自动递增选项没有开启。 我确实是手动创建的数据库,看来是忘记设置这个了……

insForm.Exec(name, city)

insForm.Exec(name, city…) 也可能返回错误。你能检查一下这个错误吗?

但您不应该需要这样做,因为字段

`id` int(6) unsigned NOT NULL AUTO_INCREMENT,

会在每次插入时自动递增。

你在终端里看到程序的任何输出吗?能看到下面这行代码的输出吗?

log.Println("INSERT: Name: " + name + " | City: " + city)

奇怪。你在程序中使用的用户是否有权限在表中执行插入操作?程序本应报错但只是检查一下。如果你使用 root 用户运行,它从一开始就拥有所有权限,所以无需检查。

是的,我确实看到了这一点。 不过在 MySQL 中我并没有看到任何变化!

再次检查。我在 Go 中看到的是:

2018/11/24 18:29:47 INSERT: Name: My name | City: My citty

我没有看到任何变化。甚至在索引页面上也没有变化。我使用MySQL Workbench查看SQL表。

如果我运行代码,我能够编辑、删除并看到变化(在索引页面和MySQL表中都有显示)。但当我想要添加并选择"新建"时,没有任何变化发生。

// 代码部分保持原样

在Golang中操作MySQL数据库时,更新和创建操作确实有一些关键区别。根据你描述的情况,问题很可能出现在处理POST请求和SQL插入语句的部分。以下是完整的示例代码,展示了如何正确实现员工信息的创建功能:

package main

import (
    "database/sql"
    "fmt"
    "html/template"
    "log"
    "net/http"
    "strconv"

    _ "github.com/go-sql-driver/mysql"
)

type Employee struct {
    Id    int
    Name  string
    City string
}

var db *sql.DB
var err error

func init() {
    db, err = sql.Open("mysql", "username:password@tcp(127.0.0.1:3306)/testdb")
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    http.HandleFunc("/", Index)
    http.HandleFunc("/show", Show)
    http.HandleFunc("/new", New)
    http.HandleFunc("/edit", Edit)
    http.HandleFunc("/insert", Insert)
    http.HandleFunc("/update", Update)
    http.HandleFunc("/delete", Delete)
    http.ListenAndServe(":8080", nil)
}

func Index(w http.ResponseWriter, r *http.Request) {
    var employees []Employee
    
    rows, err := db.Query("SELECT * FROM employees ORDER BY id DESC")
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()
    
    for rows.Next() {
        var emp Employee
        err = rows.Scan(&emp.Id, &emp.Name, &emp.City)
        if err != nil {
            log.Fatal(err)
        }
        employees = append(employees, emp)
    }
    
    t, _ := template.ParseFiles("index.html")
    t.Execute(w, employees)
}

func New(w http.ResponseWriter, r *http.Request) {
    t, _ := template.ParseFiles("new.html")
    t.Execute(w, nil)
}

func Insert(w http.ResponseWriter, r *http.Request) {
    if r.Method == "POST" {
        name := r.FormValue("name")
        city := r.FormValue("city")
        
        stmt, err := db.Prepare("INSERT INTO employees(name, city) VALUES(?, ?)")
        if err != nil {
            log.Fatal(err)
        }
        defer stmt.Close()
        
        _, err = stmt.Exec(name, city)
        if err != nil {
            log.Fatal(err)
        }
    }
    http.Redirect(w, r, "/", 301)
}

func Show(w http.ResponseWriter, r *http.Request) {
    nId := r.URL.Query().Get("id")
    
    row := db.QueryRow("SELECT * FROM employees WHERE id=?", nId)
    
    var emp Employee
    err = row.Scan(&emp.Id, &emp.Name, &emp.City)
    if err != nil {
        log.Fatal(err)
    }
    
    t, _ := template.ParseFiles("show.html")
    t.Execute(w, emp)
}

func Edit(w http.ResponseWriter, r *http.Request) {
    nId := r.URL.Query().Get("id")
    
    row := db.QueryRow("SELECT * FROM employees WHERE id=?", nId)
    
    var emp Employee
    err = row.Scan(&emp.Id, &emp.Name, &emp.City)
    if err != nil {
        log.Fatal(err)
    }
    
    t, _ := template.ParseFiles("edit.html")
    t.Execute(w, emp)
}

func Update(w http.ResponseWriter, r *http.Request) {
    if r.Method == "POST" {
        id := r.FormValue("uid")
        name := r.FormValue("name")
        city := r.FormValue("city")
        
        stmt, err := db.Prepare("UPDATE employees SET name=?, city=? WHERE id=?")
        if err != nil {
            log.Fatal(err)
        }
        defer stmt.Close()
        
        _, err = stmt.Exec(name, city, id)
        if err != nil {
            log.Fatal(err)
        }
    }
    http.Redirect(w, r, "/", 301)
}

func Delete(w http.ResponseWriter, r *http.Request) {
    nId := r.URL.Query().Get("id")
    
    stmt, err := db.Prepare("DELETE FROM employees WHERE id=?")
    if err != nil {
        log.Fatal(err)
    }
    defer stmt.Close()
    
    _, err = stmt.Exec(nId)
    if err != nil {
        log.Fatal(err)
    }
    
    http.Redirect(w, r, "/", 301)
}

对应的HTML模板文件:

new.html(用于创建新员工):

<!DOCTYPE html>
<html>
<head>
    <title>Create New Employee</title>
</head>
<body>
    <form method="POST" action="/insert">
        <label>Name:</label>
        <input type="text" name="name" required>
        <br>
        <label>City:</label>
        <input type="text" name="city" required>
        <br>
        <input type="submit" value="Create">
    </form>
</body>
</html>

index.html(员工列表页面):

<!DOCTYPE html>
<html>
<head>
    <title>Employee List</title>
</head>
<body>
    <a href="/new">Create New Employee</a>
    <table border="1">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>City</th>
            <th>Actions</th>
        </tr>
        {{range .}}
        <tr>
            <td>{{.Id}}</td>
            <td>{{.Name}}</td>
            <td>{{.City}}</td>
            <td>
                <a href="/show?id={{.Id}}">View</a> |
                <a href="/edit?id={{.Id}}">Edit</a> |
                <a href="/delete?id={{.Id}}">Delete</a>
            </td>
        </tr>
        {{end}}
    </table>
</body>
</html>

关键检查点:

  1. 确保/new路由正确指向创建表单
  2. Insert函数使用INSERT INTO语句而非UPDATE
  3. 表单的action属性指向/insert端点
  4. 数据库表结构包含自增ID字段

最常见的错误是将创建操作误用为更新操作,或者表单提交的目标端点不正确。检查你的代码中/insert端点的实现和表单的提交目标是否匹配。

回到顶部