直接在vscode终端运行:
go get -u github.com/go-sql-driver/mysql
下载完之后,导入包
import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" )
//定义全局变量db,方便之后对数据库操作 var db *sql.DB //定义一个初始化数据库函数 func initDB() (err error) { dsn := "root:密码@tcp(127.0.0.1:3306)/操作的数据库?charset=utf8mb4&parseTime=True" //打开数据库 db, err = sql.Open("mysql", dsn) if err != nil { return err } //尝试与数据库建立连接(校验dsn是否正确) err = db.Ping() if err != nil { return err } return nil }
func insertData() { //这里“?"充当占位符 sqlStr := "insert into user_tbl(username,password) values (?, ?)" //返回执行sql语句的结果集和报错 r, err := db.Exec(sqlStr, "张三", "zs123") if err != nil { fmt.Printf("insert failed,err: %v\n", err) return } else { i, _ := r.LastInsertId() fmt.Printf("i: %v\n", i) } }
type User struct { id int username string password string } func queryOneRow() { s := "select * from user_tbl where id = ?" var u User //这里scan是把前面查询结果赋值给另一个对象(User) err := db.QueryRow(s, 1).Scan(&u.id, &u.username, &u.password) if err != nil { fmt.Printf("err: %v\n", err) } else { fmt.Printf("u: %v\n", u) } }
func queryManyRow() { s := "select * from user_tbl" r, err := db.Query(s) var u User defer r.Close() if err != nil { fmt.Printf("err: %v\n", err) } else { //从结果集中遍历每行数据 for r.Next() { r.Scan(&u.id, &u.username, &u.password) fmt.Printf("u: %v\n", u) } } }
func update() { s := "update user_tbl set username=?, password=? where id=?" r, err := db.Exec(s, "big kite", "456789", 2) if err != nil { fmt.Printf("err: %v\n", err) } else { //RowsAffected返回影响了几行和错误 i, _ := r.RowsAffected() fmt.Printf("i: %v\n", i) } }
跟上述更新类似,只是sql语句不同而已
delete from user_tbl where id=?