第 0002 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。
- 创建优惠券表
mysql> create table promotion_code (
-> promotion_code varchar(255),
-> used bool,
-> );
- 生成优惠码(golang学习---练习1)
- 将生成的优惠码存入,mysql
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"log"
"time"
"math/rand"
"encoding/base64"
)
func main() {
codes := generate_code()
fmt.Println(codes)
db, err := sql.Open("mysql", "mysql:123456@/gotest?charset=utf8")
defer db.Close()
if err != nil {
log.Fatal(err)
}
for _, code := range codes {
stmt, err := db.Prepare("insert into promotion_code (promotion_code, used) values (?, ?)")
if err != nil {
log.Fatal(err)
}
_, err = stmt.Exec(code, false)
if err != nil {
log.Println(err)
}
}
}
/*
生成优惠码
*/
func generate_code() []string {
var codes []string
for i := 0; i < 200; i++ {
//
randNum := rand.Int()
//获取纳秒
t := time.Now().UnixNano()
result := fmt.Sprint(randNum) + fmt.Sprint(t)
encoded := base64.StdEncoding.EncodeToString([]byte(result))
codes = append(codes, encoded)
}
return codes
}
网友评论