/
connection.go
84 lines (67 loc) · 1.68 KB
/
connection.go
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package golangdb
import (
"database/sql"
"fmt"
)
/*
DatabaseConnection contains data necessary to establish a connection
to a database server. Most fields are useful for standard SQL
servers. The DatabaseFile field is used by SQLite.
*/
type DatabaseConnection struct {
Engine DatabaseEngine
Address string
Port int
Database string
UserName string
Password string
}
/*
Connect to a database. This method will use the specified
engine to determine how to connect.
*/
func (this *DatabaseConnection) Connect(connectionName string) error {
var db *sql.DB
var err error
switch this.Engine {
case SQLITE:
db, err = ConnectSQLite(this)
case MYSQL:
db, err = ConnectMySQL(this)
case MSSQL:
db, err = ConnectMSSQL(this)
case TESTDB:
db, err = ConnectTestDB(this)
}
if err != nil {
return err
}
Db[connectionName] = db
return nil
}
/*
This method converts a DatabaseConnection structure into a string
appropriate for connecting to a database server.
*/
func (this *DatabaseConnection) ToString() string {
switch this.Engine {
case SQLITE:
return this.toSQLiteString()
case MYSQL:
return this.toMySQLString()
case MSSQL:
return this.toMSSQLString()
case TESTDB:
return ""
}
return ""
}
func (this *DatabaseConnection) toMySQLString() string {
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?autocommit=true", this.UserName, this.Password, this.Address, this.Port, this.Database)
}
func (this *DatabaseConnection) toMSSQLString() string {
return fmt.Sprintf("Server=%s;Port=%d;User Id=%s;Password=%s;Database=%s", this.Address, this.Port, this.UserName, this.Password, this.Database)
}
func (this *DatabaseConnection) toSQLiteString() string {
return this.Database
}