9-15 2 views
建立MySQL连接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package model import ( "MySQLExport/config" "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" "log" "time" ) var db *gorm.DB func DbInit(conf) { // 创建DB连接 Db, err := gorm.Open("mysql", fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", conf.MySQLUser, conf.MySQLPassword, conf.MySQLHost, conf.MySQLPort, conf.MySQLDb), ) if err != nil { log.Println(err) log.Fatal("MySQL连接建立失败!!!") } db = Db db.DB().SetConnMaxLifetime(time.Minute * 10) db.DB().SetMaxOpenConns(50) db.DB().SetMaxIdleConns(15) } func DB() *gorm.DB { db.LogMode(config.GlobalConfig.DEBUG) return db.New() } |
调用执行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
func TestDbInit(t *testing.T) { var cnf = config.MySQLField{ MySQLHost: "127.0.0.1", MySQLPort: 3306, MySQLUser: "user", MySQLPassword: "pass", MySQLDb: "tablename", } sql := "select * from tablename" // DB初始化 model.DbInit(cnf) Db := model.DB() // 执行sql语句 log.Printf("[%v] SQL execing...\n", sql) rows, err := Db.Raw(sql).Rows() if err != nil { log.Fatal(err) } defer rows.Close() columnNames, _ := rows.Columns() count := len(columnNames) values := make([]interface{}, count) valuePtrs := make([]interface{}, count) for rows.Next() { row := make([]string, count) for i, _ := range columnNames { valuePtrs[i] = &values[i] } if err = rows.Scan(valuePtrs...); err != nil { return nil } //遍历每个字段的类型 for i, _ := range columnNames { var value interface{} rawValue := values[i] byteArray, ok := rawValue.([]byte) if ok { value = string(byteArray) } else { value = rawValue } if value == nil { row[i] = "" } else { row[i] = fmt.Sprintf("%v", value) } } log.Printf("row:::%v\n", row) } } |
如果想赏钱,可以用微信扫描下面的二维码,一来能刺激我写博客的欲望,二来好维护云主机的费用; 另外再次标注博客原地址 itnotebooks.com 感谢!