我一直在尝试将mysql与go连接,但我似乎能够成功。我只是想从表中获取一个值并将其设置为变量并打印它。我所缺少的可能只是一些明显的东西
这是来自名为bankdata的数据库
mysql> select * from accounts ;
+----+----------+-----------------+----------+---------+
| id | username | email | facebook | twitter |
+----+----------+-----------------+----------+---------+
| 1 | user1 | email1@mail.com | userfb1 | NULL |
| 2 | user2 | email2@mail.com | NULL | NULL |
| 3 | user3 | email3@mail.com | NULL | NULL |
+----+----------+-----------------+----------+---------+
我使用了两个驱动程序,我似乎可以理解它们两个有什么问题
package main
import (
"database/sql"
_ "github.com/Go-SQL-Driver/MySQL"
"log"
)
const (
DB_HOST = "tcp(127.0.0.1:3306)"
DB_NAME = "bankdata"
DB_USER = /*"root"*/ "bankadmin"
DB_PASS = /*""*/ "1234"
)
func main() {
dsn := DB_USER + ":" + DB_PASS + "@" + DB_HOST + "/" + DB_NAME + "?charset=utf8"
db, err := sql.Open("mysql", dsn)
if err != nil {
log.Fatal(err)
}
defer db.Close()
var str string
q := "select username from bankadmin.accounts where id = 1"
err = db.QueryRow(q).Scan(&str)
if err != nil {
log.Fatal(err)
}
log.Println(str)
}
返回
D:\_>go run dbtest.go
2013/03/29 13:14:11 Error 1045: Access denied for user 'bankadmin'@'localhost'
(using password: YES)
exit status 1
密码实际上是正确的,对于用户root和bankadmin,以及在端口3306中运行的mysql。但是再次,如果我将DB_HOST更改为“tcp(127.0.0.1:3000)”或更改127.0 .0.1到localhost,它给了我同样的错误。
package main
import (
"database/sql"
"fmt"
_ "github.com/ziutek/mymysql/godrv"
"log"
"strconv"
)
const (
DB_HOST = "tcp(127.0.0.1:3306)"
DB_NAME = "bankdata"
DB_USER = "bankadmin"
DB_PASS = "1234"
)
type User struct {
Id int
Username string
Email string
Facebook string
}
func OpenDB() *sql.DB {
db, err := sql.Open("mymysql", fmt.Sprintf("%s/%s/%s", DB_NAME, DB_USER, DB_PASS))
if err != nil {
panic(err)
log.Fatal(err)
}
return db
}
func UserById(id int) *User {
db := OpenDB()
defer db.Close()
row := db.QueryRow("SELECT id, username, email FROM accounts WHERE id=?", id)
user := new(User)
row.Scan(&user.Id, &user.Username, &user.Email, &user.Facebook)
return user
}
func main() {
db := OpenDB()
defer db.Close()
row := db.QueryRow("SELECT id, username, email, facebook FROM accounts WHERE id=2")
user := new(User)
row.Scan(&user.Id, &user.Username, &user.Email, &user.Facebook)
fmt.Println("id : " + strconv.Itoa(user.Id) + "\nname : " + user.Username + "\nemail : \n" + user.Email)
}
返回:
D:\_>go run dbtest.go
id : 0
name :
email :
看起来id和字符串都是空的,就像它从未从row.Scan函数接收任何值一样。并且我不知道如何确保它们已连接,即使它们没有给我与前一个驱动程序相同的错误
哦,我正在使用WAMP附带的Windows 7,MySQL 5.5.8。
如果我在这篇文章中犯了任何错误,请原谅我。这是我的第一篇文章。