go访问mysql基本语法

package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
)
/*
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)
	//	}
	//}

	//添加
	//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
	//}
	//res,err := stmt.Exec("2d2e4ebfcb864213a0b6a71d400f1cd9","test2")
	//if err != nil {
	//	fmt.Printf("Pretreatment fail [%]")
	//	return
	//}
	//num,err := res.RowsAffected()
	//if err != nil {
	//	fmt.Printf("insert fail [%s]",err)
	//}
	//fmt.Printf(" Number of rows affected  [%v]",num)


	//删除
	//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)

}

 

go访问mysql基本语法

上一篇:MySQL中一些基础查询操作(适用于MariaDB)


下一篇:修改MySQL字符集