最新消息:觉得本站不错的话 记得收藏哦 博客内某些功能仅供测试 讨论群:135931704 快养不起小站了 各位有闲钱就打赏下把 My Email weicots#gmail.com Please replace # with @

go (golang)使用mysql 数据库

Golang ajiang-tuzi 5491浏览

导入MYSQL 包

1.下载并导入数据库驱动包
官方不提供实现,先下载第三方的实现,点击这里查看各种各样的实现版本。
这里选择了Go-MySQL-Driver这个实现。地址是:https://github.com/go-sql-driver/mysql/。
然后按照里面的说明下载驱动包:
$ go get github.com/go-sql-driver/mysql
最后导入包即可:

import "database/sql"
import _ "github.com/go-sql-driver/mysql"

2.连接至数据库

db, err := sql.Open("mysql", "root:root@/uestcbook")

3.执行查询

(1)Exec 

result, err := db.Exec(
    "INSERT INTO users (name, age) VALUES (?, ?)",
    "gopher",
    27,
)
 

(2)Query 

rows, err := db.Query("SELECT name FROM users WHERE age = ?", age)
if err != nil {
    log.Fatal(err)
}
for rows.Next() {
    var name string
    if err := rows.Scan(&name); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%s is %d\n", name, age)
}
if err := rows.Err(); err != nil {
    log.Fatal(err)
}
 

(3)QueryRow

var age int64
row := db.QueryRow("SELECT age FROM users WHERE name = ?", name)
err := row.Scan(&age)
 

 

(4)Prepared statements 

age := 27
stmt, err := db.Prepare("SELECT name FROM users WHERE age = ?")
if err != nil {
    log.Fatal(err)
}
rows, err := stmt.Query(age)
// process rows
 

 

4. 事务

tx, err := db.Begin()
if err != nil {
    log.Fatal(err)
}
 

测试代码

package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
)
func main() { 
        db, _ := sql.Open("mysql", "root:root@tcp(localhost:3306)/amz?charset=utf8") 
  
        rows, _ := db.Query("select name from product_amz limit 0,100") 
	    for rows.Next() { 
		   var name string 
		     rows.Scan(&name) 
             fmt.Println(name) 
		
		}

		
  
        //db.Exec("") 
}   
 

golang

转载请注明:(●--●) Hello.My Weicot » go (golang)使用mysql 数据库

蜀ICP备15020253号-1