go-sql-driver/mysql库是Go语言官方推荐的MySQL驱动库,可以很方便地实现对MySQL数据库的连接和操作。本文记录以下使用go-sql-driver/mysql数据库驱动来操作mysql数据库。
目录
1.安装驱动程序
2.导入驱动包
3.操作数据库
3.1 获取mysql版本
3.2 创建表
3.3 表中插入数据
3.4 表中删除数据
3.5 修改表中数据
3.6 查询表中数据
3.7 删除表
4.综合演示
1.安装驱动程序
go get -u github.com/go-sql-driver/mysql
2.导入驱动包
_ "github.com/go-sql-driver/mysql"
说明:当导入带有空白标识符前缀 _ 的包时,将调用包的 init 函数。该函数注册驱动程序
3.操作数据库
3.1 获取mysql版本
func showMysqlVersion() {db, err := sql.Open("mysql", "root:mysql@tcp(127.0.0.1:3306)/TestDB?charset=utf8mb4")db.Ping()defer db.Close()if err != nil {fmt.Println("数据库连接失败!")log.Fatalln(err)}var version stringerr2 := db.QueryRow("SELECT VERSION()").Scan(&version)if err2 != nil {log.Fatal(err2)}fmt.Println(version)
}
3.2 创建表
func createTable() {db, err := sql.Open("mysql", "root:mysql@tcp(127.0.0.1:3306)/TestDB")db.Ping()defer db.Close()if err != nil {fmt.Println("connect DB error !")log.Fatalln(err)}_, err2 := db.Exec("CREATE TABLE user(id INT NOT NULL , name VARCHAR(20), PRIMARY KEY(ID));")if err2 != nil {log.Fatal(err2)}fmt.Println("successfully create table")
}
3.3 表中插入数据
func insertItem() {db, err := sql.Open("mysql", "root:mysql@tcp(127.0.0.1:3306)/TestDB?charset=utf8mb4")db.Ping()defer db.Close()if err != nil {fmt.Println("connect DB error !")log.Fatalln(err)}_, err2 := db.Query("INSERT INTO user VALUES(1, 'zhangsan')")if err2 != nil {log.Fatal(err2)}fmt.Println("successfully insert item")
}
3.4 表中删除数据
func deleteItem() {db, err := sql.Open("mysql", "root:mysql@tcp(127.0.0.1:3306)/TestDB?charset=utf8mb4")db.Ping()defer db.Close()if err != nil {fmt.Println("connect DB error !")log.Fatalln(err)}sql := "DELETE FROM user WHERE id = 1"res, err2 := db.Exec(sql)if err2 != nil {panic(err2.Error())}affectedRows, err := res.RowsAffected()if err != nil {log.Fatal(err)}fmt.Printf("delete item success, statement affected %d rows\n", affectedRows)
}
3.5 修改表中数据
func alterItem() {db, err := sql.Open("mysql", "root:mysql@tcp(127.0.0.1:3306)/TestDB?charset=utf8mb4")db.Ping()defer db.Close()if err != nil {fmt.Println("connect DB error !")log.Fatalln(err)}sql := "update user set name = ? WHERE id = ?"res, err2 := db.Exec(sql, "lisi", 1)if err2 != nil {panic(err2.Error())}affectedRows, err := res.RowsAffected()if err != nil {log.Fatal(err)}fmt.Printf("alter item success, statement affected %d rows\n", affectedRows)
}
3.6 查询表中数据
func queryItem() {db, err := sql.Open("mysql", "root:mysql@tcp(127.0.0.1:3306)/TestDB?charset=utf8mb4")db.Ping()defer db.Close()if err != nil {fmt.Println("connect DB error !")log.Fatalln(err)}var mid int = 1result, err2 := db.Query("SELECT * FROM user WHERE id = ?", mid)if err2 != nil {log.Fatal(err2)}for result.Next() {var id intvar name stringerr = result.Scan(&id, &name)if err != nil {log.Fatal(err)}fmt.Printf("id: %d, name: %s\n", id, name)}
}
3.7 删除表
func dropTable() {db, err := sql.Open("mysql", "root:mysql@tcp(127.0.0.1:3306)/TestDB")db.Ping()defer db.Close()if err != nil {fmt.Println("connect DB error !")log.Fatalln(err)}_, err2 := db.Exec("DROP TABLE user;")if err2 != nil {log.Fatal(err2)}fmt.Println("successfully drop table")
}
4.综合演示
完整代码如下:
package mainimport ("database/sql""fmt""log"_ "github.com/go-sql-driver/mysql"
)func showMysqlVersion() {db, err := sql.Open("mysql", "root:mysql@tcp(127.0.0.1:3306)/TestDB?charset=utf8mb4")db.Ping()defer db.Close()if err != nil {fmt.Println("数据库连接失败!")log.Fatalln(err)}var version stringerr2 := db.QueryRow("SELECT VERSION()").Scan(&version)if err2 != nil {log.Fatal(err2)}fmt.Println(version)
}func createTable() {db, err := sql.Open("mysql", "root:mysql@tcp(127.0.0.1:3306)/TestDB")db.Ping()defer db.Close()if err != nil {fmt.Println("connect DB error !")log.Fatalln(err)}_, err2 := db.Exec("CREATE TABLE user(id INT NOT NULL , name VARCHAR(20), PRIMARY KEY(ID));")if err2 != nil {log.Fatal(err2)}fmt.Println("successfully create table")
}func insertItem() {db, err := sql.Open("mysql", "root:mysql@tcp(127.0.0.1:3306)/TestDB?charset=utf8mb4")db.Ping()defer db.Close()if err != nil {fmt.Println("connect DB error !")log.Fatalln(err)}_, err2 := db.Query("INSERT INTO user VALUES(1, 'zhangsan')")if err2 != nil {log.Fatal(err2)}fmt.Println("successfully insert item")
}func deleteItem() {db, err := sql.Open("mysql", "root:mysql@tcp(127.0.0.1:3306)/TestDB?charset=utf8mb4")db.Ping()defer db.Close()if err != nil {fmt.Println("connect DB error !")log.Fatalln(err)}sql := "DELETE FROM user WHERE id = 1"res, err2 := db.Exec(sql)if err2 != nil {panic(err2.Error())}affectedRows, err := res.RowsAffected()if err != nil {log.Fatal(err)}fmt.Printf("delete item success, statement affected %d rows\n", affectedRows)
}func alterItem() {db, err := sql.Open("mysql", "root:mysql@tcp(127.0.0.1:3306)/TestDB?charset=utf8mb4")db.Ping()defer db.Close()if err != nil {fmt.Println("connect DB error !")log.Fatalln(err)}sql := "update user set name = ? WHERE id = ?"res, err2 := db.Exec(sql, "lisi", 1)if err2 != nil {panic(err2.Error())}affectedRows, err := res.RowsAffected()if err != nil {log.Fatal(err)}fmt.Printf("alter item success, statement affected %d rows\n", affectedRows)
}func queryItem() {db, err := sql.Open("mysql", "root:mysql@tcp(127.0.0.1:3306)/TestDB?charset=utf8mb4")db.Ping()defer db.Close()if err != nil {fmt.Println("connect DB error !")log.Fatalln(err)}var mid int = 1result, err2 := db.Query("SELECT * FROM user WHERE id = ?", mid)if err2 != nil {log.Fatal(err2)}for result.Next() {var id intvar name stringerr = result.Scan(&id, &name)if err != nil {log.Fatal(err)}fmt.Printf("id: %d, name: %s\n", id, name)}
}func dropTable() {db, err := sql.Open("mysql", "root:mysql@tcp(127.0.0.1:3306)/TestDB")db.Ping()defer db.Close()if err != nil {fmt.Println("connect DB error !")log.Fatalln(err)}_, err2 := db.Exec("DROP TABLE user;")if err2 != nil {log.Fatal(err2)}fmt.Println("successfully drop table")
}func main() {showMysqlVersion()createTable()insertItem()queryItem()alterItem()queryItem()deleteItem()dropTable()
}
运行效果:
go mod init mysql-test.go
go build mysql-test.go
./mysql-test
代码结构: