go访问mysql基本语法
package main import ( _ "context" "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" uuid "github.com/satori/go.uuid" ) /* CREATE TABLE `t_user_info` ( `uuid` varchar(32) NOT NULL COMMENT '主键UUID', `user_name` varchar(40) DEFAULT NULL DEFAULT '' COMMENT '用户名称', PRIMARY KEY (`uuid`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='用户信息'; */ func main() { db,err := sql.Open("mysql","用户名:密码@tcp(ip:3306)/库名?charset=utf8") if err != nil { fmt.Printf("connect mysql fail [%s]",err) }else { fmt.Println("connect to mysql succes.") } //查询 rows,err := db.Query("select uuid,user_name from t_user_info") if err != nil { fmt.Printf("select fail [%s]",err) return } for rows.Next() { var uuid string var user_name string rows.Columns() err := rows.Scan(&uuid, &user_name) if err != nil { fmt.Printf("get user info error [%s]", err) } else { fmt.Println(uuid, user_name) } } //开启事务 conn,err := db.Begin() if err != nil { fmt.Printf("open transaction error [%s]",err) return } //添加 stmt,err :=db.Prepare("insert into t_user_info values(?,?)") //stmt,err :=db.Prepare("insert t_user_info set uuid = ?,user_name = ?") if err != nil { fmt.Printf("Pretreatment fail [%]") return } //生成uuid开始 id,err := uuid.NewV4() if err != nil { fmt.Printf("get uuid error [%s]",err) } fmt.Printf("github.com/satori/go.uuid: %s\n", id) //生成uuid结束 res,err := stmt.Exec(id,"test3") //res,err := stmt.Exec("2d2e4ebfcb864213a0b6a71d400f1cd9","test2") if err != nil { fmt.Printf("Pretreatment fail [%]") //事务回滚 conn.Rollback() return } num,err := res.RowsAffected() if err != nil { fmt.Printf("insert fail [%s]",err) } fmt.Printf(" Number of rows affected [%v]",num) //提交事务 conn.Commit() //删除 //stmt,err :=db.Prepare("delete from t_user_info where uuid = ?") //if err != nil { // fmt.Printf("Pretreatment fail [%s]",err) // return //} //res,err := stmt.Exec("2d2e4ebfcb864213a0b6a71d400f1cd9") //if err != nil { // fmt.Printf("Pretreatment fail [%s]",err) // return //} //num,err := res.RowsAffected() //if err != nil { // fmt.Printf("delete fail [%s]",err) //} //fmt.Printf(" Number of rows affected [%v]",num) //修改 //stmt,err :=db.Prepare("update t_user_info set user_name = 'golang' where uuid = ?") //if err != nil { // fmt.Printf("Pretreatment fail [%s]",err) // return //} //res,err := stmt.Exec("7a84e9e5163d4861b341b12a536a6a0d") //if err != nil { // fmt.Printf("Pretreatment fail [%s]",err) // return //} //num,err := res.RowsAffected() //if err != nil { // fmt.Printf("update fail [%s]",err) //} //fmt.Printf(" Number of rows affected [%v]",num) }