英文:
The UPDATE SQL command doesn't work with GO language
问题
在下面的示例中,UPDATE命令无法正常工作。为什么?
详见updateDate
方法的细节。
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
type ConnData struct {
// para usar conexão via socket veja '/etc/mysql/my.cnf'
// para usar conexão via tcp confira a porta com 'ps -ef | grep mysqld'
dbuser, dbpasswd, dbname, tcp, socket string
}
var myConnData = ConnData{dbuser: "soma", dbpasswd: "secret1000",
dbname: "test",
tcp: "tcp(127.0.0.1:3307)",
socket: "unix(/tmp/mysql.sock)"}
// CREATE TABLE userinfo
// (
// uid serial NOT NULL,
// username character varying(20) NOT NULL,
// depto character varying(10) NULL,
// Created date,
// CONSTRAINT userinfo_pkey PRIMARY KEY (uid)
// )
func main() {
_ = ConnectToMySQLAndRunCmd(myConnData).(string)
}
func ConnectToMySQLAndRunCmd(connData ConnData) interface{} {
myConnStr := connData.dbuser + ":" + connData.dbpasswd +
"@" + connData.tcp + "/" + connData.dbname
log.Printf("Connecting to MySQL Server using %s\n", myConnStr)
db, err := sql.Open("mysql", myConnStr)
defer db.Close()
checkErr(err)
// Open doesn't open a connection. Validate DSN data:
err = db.Ping()
checkErr(err)
// Limpando a tabela
_, err = db.Exec("DELETE FROM userinfo")
checkErr(err)
// Consultando
selectAll(db)
// Inserindo
stmt, err := db.Prepare("INSERT INTO userinfo (username, depto, created) VALUES(?,?,?)")
checkErr(err)
res, err := stmt.Exec("Pedro", "TI", "2015-09-01")
checkErr(err)
lastId, err := res.LastInsertId()
checkErr(err)
rowCnt, err := res.RowsAffected()
checkErr(err)
log.Printf("ID = %d, affected = %d\n", lastId, rowCnt)
// Verificando
selectAll(db)
// Atualizando
updateDate(db, lastId)
// Verificando Novamente
selectAll(db)
return "OK"
}
func selectAll(mydb *sql.DB) {
// Consultando todos
var (
id int
name string
depto string
date string
)
rows, err := mydb.Query("select uid, username, depto, created from userinfo")
checkErr(err)
defer rows.Close()
for rows.Next() {
err := rows.Scan(&id, &name, &depto, &date)
checkErr(err)
log.Println(id, name, depto, date)
}
err = rows.Err()
checkErr(err)
}
func updateDate(mydb *sql.DB, lastId int64) {
// Atualizando a data
tx, err := mydb.Begin()
checkErr(err)
//...
cmd := "UPDATE userinfo SET created = ? WHERE uid = ?"
updateDate, err := tx.Prepare(cmd)
checkErr(err)
//...
log.Println("•••• Updating record", lastId)
res, err := updateDate.Exec(lastId, "2015-09-02")
checkErr(err)
// log.Println("•••• >>> ", res)
updateDate.Close()
err = tx.Commit()
checkErr(err)
affect, err := res.RowsAffected()
checkErr(err)
fmt.Println("Records affected", affect)
}
func checkErr(err error) {
if err != nil {
log.Fatal(err)
panic(err)
}
}
出了什么问题?
当我运行主程序时,下面是结果:
$ ./main
2015/09/05 14:04:34 Connecting to MySQL Server using soma:soma@tcp(127.0.0.1:3307)/test
2015/09/05 14:04:34 ID = 3, affected = 1
2015/09/05 14:04:34 3 Pedro TI 2015-09-01
2015/09/05 14:04:34 •••• Updating record 3
Records affected 0
2015/09/05 14:04:34 3 Pedro TI 2015-09-01
我使用go build -a -installsuffix cgo -o main .
来构建主程序。
英文:
In this example below the UPDATE command doesn't work. Why ?
See the updateDate
method for details.
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
type ConnData struct {
// para usar conexão via socket veja '/etc/mysql/my.cnf'
// para usar conexão via tcp confira a porta com 'ps -ef | grep mysqld'
dbuser, dbpasswd, dbname, tcp, socket string
}
var myConnData = ConnData{dbuser: "soma", dbpasswd: "secret1000",
dbname: "test",
tcp: "tcp(127.0.0.1:3307)",
socket: "unix(/tmp/mysql.sock)"}
// CREATE TABLE userinfo
// (
// uid serial NOT NULL,
// username character varying(20) NOT NULL,
// depto character varying(10) NULL,
// Created date,
// CONSTRAINT userinfo_pkey PRIMARY KEY (uid)
// )
func main() {
_ = ConnectToMySQLAndRunCmd(myConnData).(string)
}
func ConnectToMySQLAndRunCmd(connData ConnData) interface{} {
myConnStr := connData.dbuser + ":" + connData.dbpasswd +
"@" + connData.tcp + "/" + connData.dbname
log.Printf("Connecting to MySQL Server using %s\n", myConnStr)
db, err := sql.Open("mysql", myConnStr)
// myConnStr := connData.dbuser + ":" + connData.dbpasswd +
// "@" + connData.tcp + "/" + connData.dbname
defer db.Close()
checkErr(err)
// Open doesn't open a connection. Validate DSN data:
err = db.Ping()
checkErr(err)
// Limpando a tabela
_, err = db.Exec("DELETE FROM userinfo")
checkErr(err)
// Consultando
selectAll(db)
// Inserindo
stmt, err := db.Prepare("INSERT INTO userinfo (username, depto, created) VALUES(?,?,?)")
// db.Prepare("INSERT INTO users(name) VALUES(?)")
checkErr(err)
res, err := stmt.Exec("Pedro", "TI", "2015-09-01")
checkErr(err)
lastId, err := res.LastInsertId()
checkErr(err)
rowCnt, err := res.RowsAffected()
checkErr(err)
log.Printf("ID = %d, affected = %d\n", lastId, rowCnt)
// Verificando
selectAll(db)
// Atualizando
updateDate(db, lastId)
// Verificando Novamente
selectAll(db)
return "OK"
}
func selectAll(mydb *sql.DB) {
// Consultando todos
var (
id int
name string
depto string
date string
)
rows, err := mydb.Query("select uid, username, depto, created from userinfo")
checkErr(err)
defer rows.Close()
for rows.Next() {
err := rows.Scan(&id, &name, &depto, &date)
checkErr(err)
log.Println(id, name, depto, date)
}
err = rows.Err()
checkErr(err)
}
func updateDate(mydb *sql.DB, lastId int64) {
// Atualizando a data
tx, err := mydb.Begin()
checkErr(err)
//...
cmd := "UPDATE userinfo SET created = ? WHERE uid = ?"
updateDate, err := tx.Prepare(cmd)
checkErr(err)
//...
log.Println("•••• Updating record", lastId)
res, err := updateDate.Exec(lastId, "2015-09-02")
checkErr(err)
// log.Println("•••• >>> ", res)
updateDate.Close()
err = tx.Commit()
checkErr(err)
affect, err := res.RowsAffected()
checkErr(err)
fmt.Println("Records affected", affect)
}
func checkErr(err error) {
if err != nil {
log.Fatal(err)
panic(err)
}
}
What is going wrong ?
See below the result when I run the main programa.
$ ./main
2015/09/05 14:04:34 Connecting to MySQL Server using soma:soma@tcp(127.0.0.1:3307)/test
2015/09/05 14:04:34 ID = 3, affected = 1
2015/09/05 14:04:34 3 Pedro TI 2015-09-01
2015/09/05 14:04:34 •••• Updating record 3
Records affected 0
2015/09/05 14:04:34 3 Pedro TI 2015-09-01
I'm using go build -a -installsuffix cgo -o main .
to build the main program
答案1
得分: 7
看起来你颠倒了lastId和"2015-09-02"的顺序:
cmd := "UPDATE userinfo SET created = ? WHERE uid = ?"
res, err := updateDate.Exec("2015-09-02", lastId)
英文:
It seems you inverted the order of lastId and "2015-09-02":
cmd := "UPDATE userinfo SET created = ? WHERE uid = ?"
res, err := updateDate.Exec(lastId, "2015-09-02")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论