您好,登錄后才能下訂單哦!
數據的持久化是程序中必不可少的,所以編程語言中對數據庫的操作是非常重要的一塊,本文介紹Go語言對mysql數據庫的操作。
db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/betting?charset=utf8")
errDeal("連接數據庫", err)
defer db.Close()
連接參數一般有以下幾種
user@unix(/path/to/socket)/dbname?charset=utf8
user:password@tcp(localhost:5555)/dbname?charset=utf8
user:password@/dbname
user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname
// 插入數據---------------------方法1
result, err := db.Exec("INSERT INTO admin_log(admin_username,log_time,log_ip,log_type,log_desc)" +
" VALUES(?,now(),?,?,?)", "admin", "127.0.0.1", "登錄", "登錄成功")
errDeal("插入數據", err)
// 查看返回信息
count, err := result.RowsAffected()
errDeal("查看插入數據條數", err)
fmt.Printf("插入數據條數:%d\n", count)
id, err := result.LastInsertId()
errDeal("查看最后插入數據的id", err)
fmt.Printf("最后插入數據的id:%d\n", id)
// 插入數據---------------------方法2,先創建一個預處理語句,再執行
stmt, err := db.Prepare("INSERT INTO admin_log(admin_username,log_time,log_ip,log_type,log_desc)" +
" VALUES(?,now(),?,?,?)")
result1, err1 := stmt.Exec("admin", "127.0.0.1", "登錄", "登錄成功")
errDeal("方法2插入數據", err1)
fmt.Println(result1.LastInsertId())
// 刪除數據
result2, err := db.Exec("DELETE FROM admin_log WHERE id=?", 2014)
fmt.Println(result2.RowsAffected())
// 更新數據
result3, err := db.Exec("UPDATE admin_log SET log_ip=? WHERE id=?", "192.168.8.9", 2017)
fmt.Println(result3.RowsAffected())
// 先定義存儲查詢結果的變量
var rid int
var username, time, ip, logType string
var desc, remark, spare interface{} // 如果字段中可能出現值為nil的情況,可以將變量申明為interface{}類型
err2 := db.QueryRow("SELECT id,admin_username,log_time,log_ip,log_type,log_desc,remark,spare" +
" FROM admin_log WHERE id=?", 2017).Scan(&rid, &username, &time, &ip, &logType, &desc, &remark, &spare) // 傳入的是變量的指針
errDeal("查詢單條數據", err2)
fmt.Printf("id=%d,username=%s,time=%s,ip=%s,logType=%s,desc=%s,remark=%v,spare=%v\n", rid, username, time, ip, logType, desc, remark, spare)
// 查詢多條數據
rows, err3 := db.Query("SELECT admin_username,log_time,log_ip,log_type,log_desc" +
" FROM admin_log WHERE id=? OR id=?", 2017, 2019)
errDeal("查詢多條數據", err3)
// 對多條數據進行遍歷
for rows.Next() {
err4 := rows.Scan(&username, &time, &ip, &logType, &desc)
errDeal("遍歷多條數據", err4)
fmt.Printf("username=%s,time=%s,ip=%s,logType=%s,desc=%s\n", username, time, ip, logType, desc)
}
// 如果查詢中不指定具體字段,使用*
rows, err33 := db.Query("SELECT *" +
" FROM admin_log WHERE id>?", 2017)
errDeal("查詢多條數據", err33)
// 查詢所有字段名,返回string切片
columes, err333 := rows.Columns()
errDeal("rows.Columns()方法調用", err333)
fmt.Printf("%T----%v\n", columes, columes)
var scanColumes = make([]interface{}, len(columes))
var values = make([]interface{}, len(columes))
for index, _ := range scanColumes {
scanColumes[index] = &values[index]
}
for rows.Next() {
err4 := rows.Scan(scanColumes...)
errDeal("遍歷多條數據", err4)
for i, val := range values {
if strings.EqualFold(judgeType(val), "[]uint8") {
fmt.Printf("%s(%T)==%s\t", columes[i], val, val)
} else {
fmt.Printf("%s(%T)==%v\t", columes[i], val, val)
}
}
fmt.Println()
}
// 開啟事務,tx是從連接池中取出一個連接,在關閉之前都是使用這個連接,提交事務和回滾事務都是操作tx
tx, err5 := db.Begin()
errDeal("開啟事務", err5)
_, err6 := tx.Exec("UPDATE admin_log SET log_desc=? WHERE id=?", "測試事務222", 2019)
//if err6 != nil {
if err6 == nil {
tx.Rollback() // 回滾
}
tx.Commit() // 提交
// 批量數據插入
tx, err7 := db.Begin()
errDeal("數據批量插入,開啟事務", err7)
insertValues := [][]interface{}{{"admin", "127.0.0.1", "登錄", "登錄成功"},{"admin", "127.0.0.1", "刪除", "刪除數據"},{"admin", "127.0.0.1", "退出", "退出系統"}}
stmt, err8 := tx.Prepare("INSERT INTO admin_log(admin_username,log_time,log_ip,log_type,log_desc) VALUES(?,now(),?,?,?)")
errDeal("數據批量插入,預處理", err8)
for _, val := range insertValues {
_, err := stmt.Exec(val...)
if err != nil {
fmt.Printf("出現錯誤回滾,錯誤信息:%v", err)
tx.Rollback()
}
}
tx.Commit()
xdb, err9 := sqlx.Open("mysql", "root:root@tcp(127.0.0.1:3306)/betting?charset=utf8")
errDeal("sqlx連接數據庫", err9)
txx, err10 := xdb.Beginx()
errDeal("sqlx開啟事務", err10)
insertValuesx := [][]interface{}{{"admin", "127.0.0.1", "登錄", "登錄成功X"},{"admin", "127.0.0.1", "刪除", "刪除數據X"},{"admin", "127.0.0.1", "退出", "退出系統X"}}
stmtx, err11 := txx.Preparex("INSERT INTO admin_log(admin_username,log_time,log_ip,log_type,log_desc) VALUES(?,now(),?,?,?)")
errDeal("數據批量插入,預處理", err11)
for _, val := range insertValuesx {
_, err := stmtx.Exec(val...)
if err != nil {
fmt.Printf("sqlx出現錯誤回滾,錯誤信息:%v", err)
txx.Rollback()
}
}
txx.Commit()
package main
import (
"database/sql"
_"github.com/go-sql-driver/mysql" // 這里很重要,導入自己本地使用的數據庫驅動,前面是下劃線,否則會報錯:sql: unknown driver "mysql" (forgotten import?)
"fmt"
"strings"
"github.com/jmoiron/sqlx"
)
func main() {
// 連接數據庫,用戶名:密碼@協議(地址:端口)/數據庫?參數=參數值,常用"用戶名:密碼@tcp(ip:端口)/數據庫名?charset=字符集"
db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/betting?charset=utf8")
errDeal("連接數據庫", err)
defer db.Close()
//=========================================================================================增刪改
// 插入數據---------------------方法1
result, err := db.Exec("INSERT INTO admin_log(admin_username,log_time,log_ip,log_type,log_desc)" +
" VALUES(?,now(),?,?,?)", "admin", "127.0.0.1", "登錄", "登錄成功")
errDeal("插入數據", err)
// 查看返回信息
count, err := result.RowsAffected()
errDeal("查看插入數據條數", err)
fmt.Printf("插入數據條數:%d\n", count)
id, err := result.LastInsertId()
errDeal("查看最后插入數據的id", err)
fmt.Printf("最后插入數據的id:%d\n", id)
// 插入數據---------------------方法2,先創建一個預處理語句,再執行
stmt, err := db.Prepare("INSERT INTO admin_log(admin_username,log_time,log_ip,log_type,log_desc)" +
" VALUES(?,now(),?,?,?)")
result1, err1 := stmt.Exec("admin", "127.0.0.1", "登錄", "登錄成功")
errDeal("方法2插入數據", err1)
fmt.Println(result1.LastInsertId())
// 刪除數據
result2, err := db.Exec("DELETE FROM admin_log WHERE id=?", 2014)
fmt.Println(result2.RowsAffected())
// 更新數據
result3, err := db.Exec("UPDATE admin_log SET log_ip=? WHERE id=?", "192.168.8.9", 2017)
fmt.Println(result3.RowsAffected())
//=============================================================================================查詢
// 查詢單條數據
// 先定義存儲查詢結果的變量
var rid int
var username, time, ip, logType string
var desc, remark, spare interface{} // 如果字段中可能出現值為nil的情況,可以將變量申明為interface{}類型
err2 := db.QueryRow("SELECT id,admin_username,log_time,log_ip,log_type,log_desc,remark,spare" +
" FROM admin_log WHERE id=?", 2017).Scan(&rid, &username, &time, &ip, &logType, &desc, &remark, &spare) // 傳入的是變量的指針
errDeal("查詢單條數據", err2)
fmt.Printf("id=%d,username=%s,time=%s,ip=%s,logType=%s,desc=%s,remark=%v,spare=%v\n", rid, username, time, ip, logType, desc, remark, spare)
// 查詢多條數據
rows, err3 := db.Query("SELECT admin_username,log_time,log_ip,log_type,log_desc" +
" FROM admin_log WHERE id=? OR id=?", 2017, 2019)
errDeal("查詢多條數據", err3)
// 對多條數據進行遍歷
for rows.Next() {
err4 := rows.Scan(&username, &time, &ip, &logType, &desc)
errDeal("遍歷多條數據", err4)
fmt.Printf("username=%s,time=%s,ip=%s,logType=%s,desc=%s\n", username, time, ip, logType, desc)
}
// 如果查詢中不指定具體字段,使用*
rows, err33 := db.Query("SELECT *" +
" FROM admin_log WHERE id>?", 2017)
errDeal("查詢多條數據", err33)
// 查詢所有字段名,返回string切片
columes, err333 := rows.Columns()
errDeal("rows.Columns()方法調用", err333)
fmt.Printf("%T----%v\n", columes, columes)
var scanColumes = make([]interface{}, len(columes))
var values = make([]interface{}, len(columes))
for index, _ := range scanColumes {
scanColumes[index] = &values[index]
}
for rows.Next() {
err4 := rows.Scan(scanColumes...)
errDeal("遍歷多條數據", err4)
for i, val := range values {
if strings.EqualFold(checkType(val), "[]uint8") {
fmt.Printf("%s(%T)==%s\t", columes[i], val, val)
} else {
fmt.Printf("%s(%T)==%v\t", columes[i], val, val)
}
}
fmt.Println()
}
// ==================================================================================================事務
// 開啟事務,tx是從連接池中取出一個連接,在關閉之前都是使用這個連接,提交事務和回滾事務都是操作tx
tx, err5 := db.Begin()
errDeal("開啟事務", err5)
_, err6 := tx.Exec("UPDATE admin_log SET log_desc=? WHERE id=?", "測試事務222", 2019)
//if err6 != nil {
if err6 == nil {
tx.Rollback() // 回滾
}
tx.Commit() // 提交
// 批量數據插入
tx, err7 := db.Begin()
errDeal("數據批量插入,開啟事務", err7)
insertValues := [][]interface{}{{"admin", "127.0.0.1", "登錄", "登錄成功"},{"admin", "127.0.0.1", "刪除", "刪除數據"},{"admin", "127.0.0.1", "退出", "退出系統"}}
stmt, err8 := tx.Prepare("INSERT INTO admin_log(admin_username,log_time,log_ip,log_type,log_desc) VALUES(?,now(),?,?,?)")
errDeal("數據批量插入,預處理", err8)
defer stmt.Close()
// 通過循環將每條SQL的參數寫到目標表緩沖區。
for _, val := range insertValues {
_, err := stmt.Exec(val...)
if err != nil {
fmt.Printf("出現錯誤回滾,錯誤信息:%v", err)
tx.Rollback()
}
}
tx.Commit()
// 使用sqlx批量數據插入
xdb, err9 := sqlx.Open("mysql", "root:root@tcp(127.0.0.1:3306)/betting?charset=utf8")
errDeal("sqlx連接數據庫", err9)
defer xdb.close()
txx, err10 := xdb.Beginx()
errDeal("sqlx開啟事務", err10)
insertValuesx := [][]interface{}{{"admin", "127.0.0.1", "登錄", "登錄成功X"},{"admin", "127.0.0.1", "刪除", "刪除數據X"},{"admin", "127.0.0.1", "退出", "退出系統X"}}
stmtx, err11 := txx.Preparex("INSERT INTO admin_log(admin_username,log_time,log_ip,log_type,log_desc) VALUES(?,now(),?,?,?)")
errDeal("數據批量插入,預處理", err11)
defer stmtx.Close()
// 通過循環將每條SQL的參數寫到目標表緩沖區。
for _, val := range insertValuesx {
_, err := stmtx.Exec(val...)
if err != nil {
fmt.Printf("sqlx出現錯誤回滾,錯誤信息:%v", err)
txx.Rollback()
}
}
txx.Commit()
}
func errDeal(info string, err error) {
if err != nil {
panic(fmt.Sprintf("%s,錯誤信息:%v", info, err))
}
}
func checkType(val interface{}) string {
switch val.(type) {
case []uint8 :
return "[]uint8"
}
return ""
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。