Go语言学习笔记—golang操作MySQL数据库

文章目录

  • 一 准备数据库和表
  • 二 安装配置mysql驱动
  • 三 获得数据库连接
    • 3.1 导入包
    • 3.2 获得连接
    • 3.3 初始化连接
  • 四 插入数据
  • 五 查询数据
    • 5.1 单行查询
    • 5.2 多行查询
  • 六 更新数据
  • 七 删除数据


一 准备数据库和表

创建一个go_db数据库

create database go_db;

打开数据库

use go_db;

创建表

 create table user_tb1(
     id integer primary key auto_increment,
     username varchar(20),
     password varchar(20)
 );

添加模拟数据

insert into user_tb1(username,password) value("psych","666");
insert into user_tb1(username,password) value("tom","123");
insert into user_tb1(username,password) value("kitte","456");

详细过程:

C:\Users\Mechrevo>mysql -uroot -p
Enter password: ******
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.19 MySQL Community Server - GPL

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database go_db;
Query OK, 1 row affected (0.44 sec)

mysql> use go_db;
Database changed

mysql> create table user_tb1(id integer primary key auto_increment,username varchar(20),password varchar(20));
Query OK, 0 rows affected (1.10 sec)

mysql> desc user_tb1;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| id       | int         | NO   | PRI | NULL    | auto_increment |
| username | varchar(20) | YES  |     | NULL    |                |
| password | varchar(20) | YES  |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+
3 rows in set (0.23 sec)

mysql> insert into user_tb1(username,password) value("psych","666");
Query OK, 1 row affected (0.47 sec)

mysql> insert into user_tb1(username,password) value("tom","123");
Query OK, 1 row affected (0.17 sec)

mysql> insert into user_tb1(username,password) value("kitte","456");
Query OK, 1 row affected (0.09 sec)

mysql> select * from user_tb1;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
|  1 | psych    | 666      |
|  2 | tom      | 123      |
|  3 | kitte    | 456      |
+----+----------+----------+
3 rows in set (0.03 sec)

mysql>

二 安装配置mysql驱动

安装驱动

go get -u github.com/go-sql-driver/mysql

初始化模块

go mod init m

执行go mod tidy

go mod tidy

导入驱动(官方示例https://pkg.go.dev/github.com/go-sql-driver/[email protected]#section-readme)

package main

import (
	"database/sql"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

func main() {
   
	// ...

	db, err := sql.Open("mysql", "user:password@/dbname")
	if err != nil {
   
		panic(err)
	}
	// See "Important settings" section.
	db.SetConnMaxLifetime(time.Minute * 3)
	db.SetMaxOpenConns(10)
	db.SetMaxIdleConns(10)
}

三 获得数据库连接

3.1 导入包

import (
	"database/sql"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

3.2 获得连接

package main

import (
	"database/sql"
	"fmt"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

// ...
func main() {
   
	db, err := sql.Open("mysql", "root:960690@/go_db")
	if err != nil {
   
		panic(err)
	}
	// 设置最大连接时长
	db.SetConnMaxLifetime(time.Minute * 3)
    
	// 设置最大连接数
	db.SetMaxOpenConns(10)
	
	// 设置空闲连接数
	db.SetMaxIdleConns(10)

	fmt.Printf("db:%v\n", db)

}

运行结果:

[Running] go run "e:\golang开发学习\go_pro\test.go"
db:&{
   0 0xc000006028 0 {
   0 0} [] map[] 0 0 0xc00005c0c0 false map[] map[] 10 10 180000000000 0 <nil> 0 0 0 0 0x54a100}

[Done] exited with code=0 in 2.423 seconds

3.3 初始化连接

Open函数只是验证格式是否正确,实际上并不是创建数据库连接。如果要检查数据源的名称是否真实有效,应该调用Ping方法。

返回的DB对象可以安全地被多个协程并发使用,并且维护其自己的空闲连接池。因此Open函数应该仅被调用一次,很少需要关闭这个DB对象。

package main

import (
	"database/sql"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
)

// 定义一个全局对象db
var db *sql.DB

// 定义一个初始化数据库的函数
func initDB() (err error) {
   
	// dsn := "root:960690@tcp(127.0.0.1:3306)/go_db?charset=utf8mb4&parseTime=True"
	dsn := "root:960690@tcp(127.0.0.1:3306)/go_db?charset=utf8mb4"

	db, err = sql.Open("mysql"

你可能感兴趣的:(Go语言进阶学习笔记,MySQL,数据库,mysql,golang)