萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MySQL 教學

Go 語言連接 MySQL 完整實戰:從安裝、建庫、建表到程式碼查詢

環境

  • OS:Ubuntu
  • Go 版本:1.16+ (支援 modules)
  • 驅動:github.com/go-sql-driver/mysql

1. 安裝 MySQL 並建立測試資料

sudo apt-get install mysql-server  # 記住 root 密碼,假設 root123
mysql -uroot -p
CREATE DATABASE people;
GRANT ALL PRIVILEGES ON people.* TO 'peo'@'localhost' IDENTIFIED BY 'peo123';
GRANT ALL PRIVILEGES ON people.* TO 'peo'@'%' IDENTIFIED BY 'peo123';  -- 允許遠程
EXIT;

2. 開放遠程連線 (如需)

sudo nano /etc/mysql/my.cnf
# bind-address = 127.0.0.1  →  bind-address = 0.0.0.0 (或具體 IP)
sudo systemctl restart mysql

3. 建表與測試資料

mysql -u peo -p
USE people;
CREATE TABLE hello (age INT, name VARCHAR(10));
INSERT INTO hello VALUES (19, 'hello world');

4. 下載驅動

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

5. Go 完整程式碼

package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
)

type User struct {
	Age  int    `json:"age"`
	Name string `json:"name"`
}

func main() {
	fmt.Println("start")

	dsn := "peo:peo123@tcp(192.168.0.58:3306)/people?charset=utf8mb4&parseTime=true"
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		panic(err)
	}
	defer db.Close()

	rows, err := db.Query("SELECT age, name FROM hello")
	if err != nil {
		panic(err)
	}
	defer rows.Close()

	for rows.Next() {
		u := &User{}
		if err := rows.Scan(&u.Age, &u.Name); err != nil {
			panic(err)
		}
		b, _ := json.Marshal(u)
		fmt.Println(string(b))
	}
	fmt.Println("end")
}

關鍵點

  • DSN 格式:user:pass@tcp(host:port)/dbname?charset=utf8mb4&parseTime=true。
  • 匿名導入驅動 _ "github.com/go-sql-driver/mysql" 註冊 driver。
  • defer rows.Close() 釋放結果集游標。
  • parseTime=true 自動將 DATETIME 轉為 time.Time。
copyright © 萬盛學電腦網 all rights reserved