• 周日. 6 月 16th, 2024

    GO访问数据库MySQL

    root

    10 月 31, 2019 #Go, #MySQL

    安装驱动库,利用gopm

    gopm get -g -v github.com/go-sql-driver/mysql

    例子

    package main
    
    import (
    	"database/sql"
    	"fmt"
    	_ "github.com/go-sql-driver/mysql"
    )
    
    const (
    	mysql_user = "root"
    	mysql_passwd = "xxxx"
    	mysql_ip = "xxx.168.229.138"
    	mysql_port = "3306"
    	mysql_db = "test"
    )
    
    func main() {
    	dataSourceName := mysql_user+":"+mysql_passwd+"@tcp("+mysql_ip+":"+mysql_port+")/"+mysql_db+"?charset=utf8"
    	db, e := sql.Open("mysql", dataSourceName)
    	if e != nil {
    		panic(e)
    	}
    	defer db.Close()
    
    	/*var id int
    	var userName, password string
    	errTables := db.QueryRow("SELECT * FROM user").Scan(&id, &userName, &password)
    	if errTables != nil {
    		panic(errTables)
    	}
    
    	fmt.Printf("id:%d, userName:%s, password:%s\n", id, userName,password)*/
    
    	rows, e := db.Query("select * from user")
    	if e != nil {
    		panic(e)
    	}
    
    	var id int
    	var username,password string
    	for rows.Next() {
    		e := rows.Scan(&id, &username, &password)
    		if e != nil {
    			panic(e)
    		}
    		fmt.Printf("%d\t%s\t%s\n", id, username, password)
    	}
    }

    root

    发表回复