go 语言连接mysql server

东郭赞
2023-12-01

package main

import (
“database/sql”
“fmt”
_ “github.com/go-sql-driver/mysql”
)

func main() {
user := “root”
passwd := “abc.123”
addr := “47.105.88.20:3306”
dbname := “htz_sutra”
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4", user, passwd, addr, dbname)
db, err := sql.Open(“mysql”, dsn)
fmt.Println(db)
fmt.Println(err)

stmt, err := db.Prepare("INSERT INTO user_info SET username=?,departname=?,create_time=?")
if err != nil {
	fmt.Println(err)
	return
}
res, err := stmt.Exec("nulige", "商务部", "2019-1-28")
id, err := res.LastInsertId()
if err != nil {
	panic(err)
}

fmt.Println(id)

}

 类似资料: