不想多说话,先把golang和mysql连接好,环境配置好,然后直接上代码就行了,代码可直接运行。
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// MySQL 连接字符串
dbConnectionString := "root:nmnmnm67890890@tcp(localhost:3306)/test1"
// 打开数据库连接
db, err := sql.Open("mysql", dbConnectionString)
if err != nil {
panic(err.Error())
}
defer db.Close()
// 尝试连接数据库
err = db.Ping()
if err != nil {
panic(err.Error())
}
fmt.Println("Successfully connected to the database!")
// 创建表
_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS users (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
age INT NOT NULL,
PRIMARY KEY (id)
)
`)
if err != nil {
panic(err.Error())
}
fmt.Println("Table 'users' created successfully!")
// 插入一条数据
_, err = db.Exec("INSERT INTO users (name, age) VALUES (?, ?)", "John Doe", 30)
if err != nil {
panic(err.Error())
}
fmt.Println("Data inserted successfully!")
// 查询数据
rows, err := db.Query("SELECT * FROM users")
if err != nil {
panic(err.Error())
}
defer rows.Close()
// 遍历查询结果
for rows.Next() {
var id int
var name string
var age int
err := rows.Scan(&id, &name, &age)
if err != nil {
panic(err.Error())
}
fmt.Printf("ID: %d, Name: %s, Age: %d\n", id, name, age)
}
// 检查可能的错误
if err := rows.Err(); err != nil {
panic(err.Error())
}
}
看运行结果