package main
import (
"database/sql"
"flag"
"fmt"
"time"
//导入mysql的驱动
_ "github.com/go-sql-driver/mysql"
)
func main(){
/*
定义变量接收控制台参数
*/
// 用户
var username string
// 密码
var password string
// 主机名
var host string
// 端口号
var port int
// 运行次数
var totalrun int
// 请求间隔时间(s)
var sleeptime float64
// 建库建表语句
var createDB_TABLE string
var content = `create database IF NOT EXISTS shxtest;
CREATE TABLE IF NOT EXISTS shxtest.user (
user_id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '用户编号',
user_name VARCHAR(45) NOT NULL COMMENT '用户名称',
user_age TINYINT(3) UNSIGNED NOT NULL DEFAULT 0 COMMENT '用户年龄',
user_sex TINYINT(3) UNSIGNED NOT NULL DEFAULT 0 COMMENT '用户性别',
PRIMARY KEY (user_id))
ENGINE = InnoDB
AUTO_INCREMENT = 1
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci
COMMENT = '用户表';`
// StringVar用指定的名称、控制台参数项目、默认值、使用信息注册一个string类型flag,并将flag的值保存到p指向的变量
flag.StringVar(&username, "u", "", "用户名,默认为空")
flag.StringVar(&password, "p", "", "密码,默认为空")
flag.StringVar(&host, "h", "127.0.0.1", "主机名,默认 127.0.0.1")
flag.IntVar(&port, "P", 3306, "端口号,默认为3306")
flag.IntVar(&totalrun, "cts", 1,"执行次数,默认为1")
flag.Float64Var(&sleeptime, "slpt", 1000, "请求间隔时间ms,默认为1000ms")
flag.String(createDB_TABLE, content,"需提前创建shxtest库和user表,如语句")
// 从arguments中解析注册的flag。必须在所有flag都注册好而未访问其值时执行。未注册却使用flag -help时,会返回ErrHelp。
flag.Parse()
// 打印
fmt.Println("username=%v password=%v host=%v port=%v totalrun=%v sleeptime=%v", username, password, host, port, totalrun, sleeptime)
runinsert(username,password,host,port,totalrun,sleeptime)
fmt.Println("The end!")
}
func runinsert(username string,password string,host string,port int,totalrun int,sleeptime float64){
var i = 1
var constring = ""
for i <= totalrun {
constring = fmt.Sprintf("%s:%s@tcp(%s:%d)/shxtest?charset=utf8",username,password,host,port)
fmt.Println(constring)
//使用database/sql包中的Open连接数据库
db,err := sql.Open("mysql",constring)
if err != nil {
fmt.Println("连接数据库失败:",err)
return
}
//使用DB结构体实例方法Prepare预处理插入,Prepare会返回一个stmt对象
stmt,err := db.Prepare("insert into `user`(user_name,user_age,user_sex)values(?,?,?)")
if err!=nil{
fmt.Println("预处理失败:",err)
return
}
//使用Stmt对象执行预处理参数
result,err := stmt.Exec("pengjin",i,1)
if err!=nil{
fmt.Println("执行预处理失败:",err)
return
}else{
rows,_ := result.RowsAffected()
fmt.Println("执行成功,影响行数",rows,"行" )
}
stmt.Close()
db.Close()
time.Sleep(time.Duration(sleeptime * 10e5))
i++
}
}
/*
create database IF NOT EXISTS shxtest;
CREATE TABLE IF NOT EXISTS `shxtest`.`user` (
`user_id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '用户编号',
`user_name` VARCHAR(45) NOT NULL COMMENT '用户名称',
`user_age` TINYINT(3) UNSIGNED NOT NULL DEFAULT 0 COMMENT '用户年龄',
`user_sex` TINYINT(3) UNSIGNED NOT NULL DEFAULT 0 COMMENT '用户性别',
PRIMARY KEY (`user_id`))
ENGINE = InnoDB
AUTO_INCREMENT = 1
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci
COMMENT = '用户表';*/
可以把return注释掉来进行异常情况错误抛出,继续往下执行