goland 新建

Environment: https://goproxy.cn,direct
package main

import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql" //init()
"time"
)
var db sql.DB
func initMySQL()(err error) {
// DSN:Data Source Name
//dsn := "User:[email protected](127.0.0.1:3306)/dbname"
dsn := "root:[email protected](127.0.0.1:3306)/m9"
db, err = sql.Open("mysql",dsn)
if err != nil {
panic(err)
}
//嘗試與數據庫建立連接
err = db.Ping()
if err != nil {
fmt.Println("connet error")
return
}
db.SetConnMaxIdleTime(time.Second
10)
db.SetMaxOpenConns(200) // 最大連接數
db.SetMaxIdleConns(10) //最大空閒連接數
return
}
func main() {
if err := initMySQL();err!=nil {
fmt.Printf("connect err:%v\n", err)
}
defer db.Close() //關閉連接,需要放在err後
fmt.Println("connect success")
}
type user struct {
id int
name string
}
//查詢單條數據示例
func queryRowDemo() {
sqlStr := "select id, name from staff where id=?"
var u user
//非常重要:確保QueryRow之後調用Scan方法,否則持有的數據庫連接不會被釋放
row := db.QueryRow(sqlStr,1)
err := row.Scan(&u.id, &u.name)
if err != nil {
fmt.Printf("scan failed, err:%v\n", err)
return
}
fmt.Printf("id:%d name:%d",u.id, u.name)
}
//查詢多條數據
func queryMultiRowDemo() {
sqlStr := "select id, name from staff where id < ?"
rows, err := db.Query(sqlStr,8)
if err != nil {
fmt.Printf("query faild, err:%v\n", err)
return
}
//非常重要:關閉rows釋放持有的數據庫連接
defer rows.Close()
//循環讀取結果集中的數據
for rows.Next() {
var u user
err := rows.Scan(&u.id, &u.name)
if err != nil {
fmt.Printf("Scan failed, err:%v\n", err)
return
}
fmt.Printf("id:%d name:%s",u.id, u.name)
}
}
//插入數據
func insertRowDemo() {
sqlStr := "insert into staff(id,name)values(?,?)"
ret, err := db.Exec(sqlStr, 4, "zhang")
if err != nil {
fmt.Printf("insert failed, err:%v\n", err)
return
}
var theID int64
theID, err = ret.LastInsertId() //新插入數據的id
if err != nil {
fmt.Printf("get lastinsert ID failed, err:%v\n", err)
return
}
fmt.Printf("insert success, hte id is %d.\n", theID)
}
//更新數據
func updateRowDemo() {
sqlStr := "update staff set name=? where id = ?"
ret, err := db.Exec(sqlStr, "zhang",2)
if err != nil {
fmt.Printf("update failed, err:%v\n", err)
return
}
n, err := ret.RowsAffected() // 操作影響的行數
if err != nil {
fmt.Printf("get RowsAffected failed, err:%v\n", err)
return
}
fmt.Printf("update success, affected rows:%d\n", n)
}
//刪除數據
func deleteRowDemo() {
sqlStr := "delete from staff where id = ?"
ret, err := db.Exec(sqlStr, 2035)
if err != nil {
fmt.Printf("delete failed, err:%v\n", err)
return
}
n, err := ret.RowsAffected() //操作影響的行數
if err != nil {
fmt.Printf("get RowsAffected failed, err:%v\n", err)
return
}
fmt.Printf("delete success, affected rows:%d\n", n)
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章