使用golang连接MySQL报错:
panic: Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''runoob_title', 'runoob_author', 'submission_date') VALUES ("学习 MySQL", "' at line 1
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "mytest:123456@tcp(192.168.0.106:3306)/test")
defer db.Close()
if err != nil {
log.Fatal(err)
}
sql := "INSERT INTO runoob_tbl ('runoob_title', 'runoob_author', 'submission_date') VALUES (\"学习 MySQL\", \"菜鸟教程\", NOW());"
res, err := db.Exec(sql)
if err != nil {
panic(err.Error())
}
lastId, err := res.LastInsertId()
if err != nil {
log.Fatal(err)
}
fmt.Printf("The last inserted row id: %d\n", lastId)
}
找了很久,发现insert语句的语法有点问题,这一点与sqlite不一样,字段名不支持单引号,修改成如下代码即可:
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "mytest:123456@tcp(192.168.0.106:3306)/test")
defer db.Close()
if err != nil {
log.Fatal(err)
}
sql := "INSERT INTO runoob_tbl (`runoob_title`, `runoob_author`, `submission_date`) VALUES (\"学习 MySQL\", \"菜鸟教程\", NOW());"
res, err := db.Exec(sql)
if err != nil {
panic(err.Error())
}
lastId, err := res.LastInsertId()
if err != nil {
log.Fatal(err)
}
fmt.Printf("The last inserted row id: %d\n", lastId)
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)