go客户之搭建数据库
source link: https://blog.51cto.com/u_3764469/5660140
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
go客户之搭建数据库
精选 原创1、建立数据库cus,建表user,四个字段id,username:登录名,password:密码,realname:真实姓名,id字段是自增长,其他都是字符串。
2、建表customer,有id,name:名称,taxno:税号,addr:地址,contact:联系人,contel:电话,content:备注,addtime:添加时间这几个字段,id也是自增长。
3、安装mysql包 go get github.com/go-sql-driver/mysql
4、在项目中建立文件夹dbdata,数据库中的操作都放这里
在dbdata文件夹下面创建文件dbdata.go,内容如下
import (
"cus/logger"
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
var Db *sql.DB
// connect to the Db
func init() {
var err error
Db, err = sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/cus?parseTime=True&loc=Local")
if err != nil {
fmt.Println(err)
logger.Log.Error(err)
panic(err)
}
}
这里面需要注意的是parseTime=True&loc=Local这2项,在查询客户表的时候,由于addtime是datetime类型,结构体是*time.Time类型,会报错unsupported Scan, storing driver.Value type []uint8 into type *time.Time,加上parseTime=True就不出错了。加上loc=Local是为了使用time.Now()获取当前时间,不加的话插入数据库会相差8小时。至此数据库连接建立完毕
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK