先要下载驱动包,放到$GOPATH/src目录里: https://github.com/Go-SQL-Driver/MySQL
数据库:test 表:user 字段:id,name,view
package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" "log" ) var ( dbhostsip = "127.0.0.1:3306" dbusername = "root" dbpassowrd = "root" dbname = "test" ) type mysql_db struct { db *sql.DB } func (f *mysql_db) mysql_open() { Odb, err := sql.Open("mysql", dbusername+":"+dbpassowrd+"@tcp("+dbhostsip+")/"+dbname) if err != nil { log.Fatalln(err) fmt.Println("链接失败") //return nil } //defer Odb.Close() fmt.Println("链接成功") f.db = Odb } func (f *mysql_db) mysql_close() { //关闭 defer f.db.Close() } func (f *mysql_db) mysql_select(sql_data string) { //select 查询数据 rows, err := f.db.Query(sql_data) if err != nil { log.Fatalln(err) } for rows.Next() { var id int var name string var view string err = rows.Scan(&id, &name, &view) if err != nil { panic(err) } fmt.Println("file:", name) } } func (f *mysql_db) mysql_insert() { //insert 添加数据 stmt, err := f.db.Prepare("INSERT INTO user(name,view) VALUES(?,?)") //defer stmt.Close() if err != nil { log.Println(err) return } stmt.Exec("cc", "dddwwe") //http://blog.csdn.net/a32132100/article/details/8949735 // id, err := res.LastInsertId() // if err != nil { // log.Println(err) // return // } // fmt.Println(id) } func (f *mysql_db) mysql_update() { //update 修改数据 } func (f *mysql_db) mysql_delete() { //delete 删除数据 } func main() { db := &mysql_db{} db.mysql_open() db.mysql_insert() db.mysql_select("select * from user") db.mysql_close() //关闭 }
附件:源代码下载