本文记录如何利用golang实现对数据库的基本应用。
导入包
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
获取数据库连接代码
注意创建全局变量 db *sql.DB
package test_sql
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
var db *sql.DB
func InitDB() (err error) {
dsn := "root:adss123@tcp(127.0.0.1:3306)/go_db?charset=utf8mb4&parseTime=True"
db, err = sql.Open("mysql", dsn)
if err != nil {
return err
}
err = db.Ping()
if err != nil {
return err
}
return nil
}
main函数中调用连接数据库函数
package main
import "go/src/pkg/test_sql"
func main() {
err := test_sql.InitDB()
if err != nil {
println("失败")
println(err)
} else {
println("成功")
}
}
插入数据
插入,更新和删除操作都利用Exec方法
func (db *DB) Exec(query string,args ...interface{})(Result,error)
插入函数样例
func InsertData(username string, password string) {
sqlStr := "insert into user_tb1(username,password) value(?,?)"
ret, err := db.Exec(sqlStr, username, password)
if err != nil {
fmt.Printf("insert failed,err:%v\n", err)
return
}
theId, err := ret.LastInsertId()
if err != nil {
fmt.Printf("LastInsert failed,err:%v\n", err)
return
}
fmt.Printf("成功,the id is%v\n", theId)
}
main函数调用此方法
func main(){
tset_sql.InsertData("牛二炮","123456")
}
数据查询
查询单行
单行查询利用QueryRow()方法执行一次查询,并期望返回最多一行结果。QueryRow总是返回非nil的值,知道返回值被Scan方法调用时,才会返回被延迟的错误。
先定义一个结构体
type user struct{
id int
username string
password string
}
查询单行代码
func QueryOneRow(id int) {
sqlStr := "select * from user_tb1 where id=?"
var user User
err := db.QueryRow(sqlStr, id).Scan(&user.id, &user.username, &user.password)
if err != nil {
fmt.Printf("select failed,err:%v\n", err)
} else {
fmt.Printf("User:%v\n", user)
}
}
查询多行代码
func QueryManyRows() {
s := "select * from user_tb1"
query, err := db.Query(s)
defer query.Close()
if err != nil {
fmt.Printf("err:%v\n", err)
} else {
for query.Next() {
var user User
err := query.Scan(&user.id, &user.username, &user.password)
if err != nil {
println(err)
} else {
fmt.Println(user)
}
}
}
}
更新数据
插入,更新和删除操作都利用Exec方法
func (db *DB) Exec(query string,args ...interface{})(Result,error)
更新数据代码
func UpdateData(username string, password string, id int) {
sqlStr := "update user_tb1 set username=?,password=? where id=?"
result, err := db.Exec(sqlStr, username, password, id)
if err != nil {
fmt.Printf("update failed,err:%v\n", err)
return
}
rowsAffected, err := result.RowsAffected()
if err != nil {
fmt.Printf("affected failed,err:%v\n", err)
return
}
fmt.Printf("更新成功,id:%v\n", rowsAffected)
}
删除数据
插入,更新和删除操作都利用Exec方法
func (db *DB) Exec(query string,args ...interface{})(Result,error)
删除数据代码
func DelData(id int) {
sqlStr := "delete from user_tb1 where id=?"
result, err := db.Exec(sqlStr, id)
if err != nil {
fmt.Printf("del failed,err:%v\n", err)
return
}
rowsAffected, err := result.RowsAffected()
if err != nil {
fmt.Printf("affected failed,err:%v\n", err)
return
}
fmt.Printf("更新成功,id:%v\n", rowsAffected)
}