Skip to content

Commit 4bf4b19

Browse files
committed
修复不写dbname无法设置超时问题
1 parent 469b513 commit 4bf4b19

File tree

1 file changed

+7
-12
lines changed

1 file changed

+7
-12
lines changed

orm/db.go

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ type DB struct {
1717
UserName string
1818
Passwd string
1919
Charset string
20-
TimeOut int
20+
Timeout int
2121
}
2222

2323
//NewDB create db instance, timeout 单位:秒.
@@ -29,7 +29,7 @@ func NewDB(ip string, port int, dbName, user, pass, charset string, timeout int)
2929
UserName: user,
3030
Passwd: pass,
3131
Charset: charset,
32-
TimeOut: timeout,
32+
Timeout: timeout,
3333
}
3434
}
3535

@@ -50,15 +50,10 @@ func (db *DB) GetConnection() (*sql.DB, error) {
5050
}
5151

5252
func (db *DB) getDSN() string {
53-
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/", db.UserName, db.Passwd, db.IP, db.Port)
53+
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", db.UserName, db.Passwd, db.IP, db.Port, db.DBName)
5454

55-
if len(db.DBName) > 0 {
56-
dsn = fmt.Sprintf("%s%s", dsn, db.DBName)
57-
58-
optStr := db.getOpt()
59-
if len(optStr) > 0 {
60-
dsn = fmt.Sprintf("%s?%s", dsn, optStr)
61-
}
55+
if optStr := db.getOpt(); optStr != "" {
56+
dsn = fmt.Sprintf("%s?%s", dsn, optStr)
6257
}
6358

6459
return dsn
@@ -70,8 +65,8 @@ func (db *DB) getOpt() string {
7065
opts = append(opts, fmt.Sprintf("charset=%s", db.Charset))
7166
}
7267

73-
if db.TimeOut > 0 {
74-
opts = append(opts, fmt.Sprintf("timeout=%ds", db.TimeOut))
68+
if db.Timeout > 0 {
69+
opts = append(opts, fmt.Sprintf("timeout=%ds", db.Timeout))
7570
}
7671

7772
return strings.Join(opts, "&")

0 commit comments

Comments
 (0)