go_databasetest go语言的数据库测试:
代码语言:javascript复制go get github.com/Go-SQL-Driver/MySQL
package main
import (
_"github.com/Go-SQL-Driver/MySQL"
"database/sql"
"fmt"
)
func main() {
//链接数据库
db, err := sql.Open("mysql", "root:1111@tcp(127.0.0.1:3306)/test?charset=utf8")
checkErr(err)
//插入数据
stmt, err := db.Prepare("INSERT test_base SET id=?,name=?,birth=?,sex=?")
checkErr(err)
res, err := stmt.Exec("1", "百哥", "1992-3-25", "1")
checkErr(err)
id, err := res.LastInsertId()
checkErr(err)
//插入成功后返回了一个0
fmt.Println(id)
//更新数据
//根据id查找name
stmt, err = db.Prepare("update test_base set name=? where id=?")
checkErr(err)
//将name改成baige
res, err = stmt.Exec("baige", 2)
checkErr(err)
affect, err := res.RowsAffected()
checkErr(err)
fmt.Println(affect)
//查询数据
rows, err := db.Query("SELECT * FROM test_base")
checkErr(err)
for rows.Next() {
var id int
var name string
var birth string
var sex string
err = rows.Scan(&id, &name, &birth, &sex)
checkErr(err)
fmt.Println(id)
fmt.Println(name)
fmt.Println(birth)
fmt.Println(sex)
}
//删除数据
stmt, err = db.Prepare("delete from test_base where id=?")
checkErr(err)
res, err = stmt.Exec(1)
checkErr(err)
affect, err = res.RowsAffected()
checkErr(err)
fmt.Println(affect)
db.Close()
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}