|
|
@@ -6,59 +6,21 @@ import (
|
|
|
"github.com/jmoiron/sqlx"
|
|
|
)
|
|
|
|
|
|
-var (
|
|
|
- userName string = "root"
|
|
|
- password string = "jEER3Dc="
|
|
|
- ipAddrees string = "47.110.138.172"
|
|
|
- port int = 3306
|
|
|
- dbName string = "newDB"
|
|
|
- charset string = "utf8"
|
|
|
-)
|
|
|
+type Config struct {
|
|
|
+ UserName string
|
|
|
+ Password string
|
|
|
+ Ip string
|
|
|
+ Port int
|
|
|
+ DbName string
|
|
|
+ Charset string
|
|
|
+}
|
|
|
|
|
|
-func connectMysql() *sqlx.DB {
|
|
|
- dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s", userName, password, ipAddrees, port, dbName, charset)
|
|
|
+// 连接数据库
|
|
|
+func ConnectMysql(conf *Config) *sqlx.DB {
|
|
|
+ dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s", conf.UserName, conf.Password, conf.Ip, conf.Port, conf.DbName, conf.Charset)
|
|
|
Db, err := sqlx.Open("mysql", dsn)
|
|
|
if err != nil {
|
|
|
fmt.Printf("mysql connect failed, detail is [%v]", err.Error())
|
|
|
}
|
|
|
return Db
|
|
|
}
|
|
|
-
|
|
|
-func queryData(Db *sqlx.DB) {
|
|
|
- rows, err := Db.Query("select user_id as userId, user_name as userName from sys_user")
|
|
|
- if err != nil {
|
|
|
- fmt.Printf("query faied, error:[%v]", err.Error())
|
|
|
- return
|
|
|
- }
|
|
|
- for rows.Next() {
|
|
|
- //定义变量接收查询数据
|
|
|
- var userId, userName string
|
|
|
-
|
|
|
- err := rows.Scan(&userId,&userName)
|
|
|
- if err != nil {
|
|
|
- fmt.Printf("get data failed, error:[%v]", err.Error())
|
|
|
- }
|
|
|
- fmt.Println(userId, userName)
|
|
|
- }
|
|
|
-
|
|
|
- //关闭结果集(释放连接)
|
|
|
- rows.Close()
|
|
|
-}
|
|
|
-
|
|
|
-func selectData(Db *sqlx.DB) {
|
|
|
- type userInfo struct {
|
|
|
- UserId string `db:"user_id"`
|
|
|
- UserName string `db:"user_name"`
|
|
|
- }
|
|
|
-
|
|
|
- var userInfos []userInfo
|
|
|
- err := Db.Select(&userInfos, "select user_id, user_name from sys_user")
|
|
|
- if err!= nil {
|
|
|
- fmt.Printf("query fail : [%v]" , err)
|
|
|
- return
|
|
|
- }
|
|
|
-
|
|
|
- for _, user := range userInfos {
|
|
|
- fmt.Println(user.UserId,"=>", user.UserName)
|
|
|
- }
|
|
|
-}
|