1

go客户之搭建数据库

 2 years ago
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.
neoserver,ios ssh client

go客户之搭建数据库

精选 原创

zzxiaoma 2022-09-08 09:01:51 博主文章分类:go ©著作权

文章标签 sql mysql 字段 文章分类 Go语言 编程语言 私藏项目实操分享 阅读数233

1、建立数据库cus,建表user,四个字段id,username:登录名,password:密码,realname:真实姓名,id字段是自增长,其他都是字符串。

go客户之搭建数据库_mysql

2、建表customer,有id,name:名称,taxno:税号,addr:地址,contact:联系人,contel:电话,content:备注,addtime:添加时间这几个字段,id也是自增长。

go客户之搭建数据库_字段_02

3、安装mysql包 go get github.com/go-sql-driver/mysql

4、在项目中建立文件夹dbdata,数据库中的操作都放这里

在dbdata文件夹下面创建文件dbdata.go,内容如下

package dbdata

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小时。至此数据库连接建立完毕


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK