1 package myDB
2
3 import (
4 "database/sql"
5 "errors"
6
7 _ "github.com/lib/pq"
8 )
9
10 var db *sql.DB = nil
11
12 func OpenSql() error {
13 var err error = nil
14 db, err = sql.Open("postgres", "port=5432 user=postgres password=123456 dbname=postgres sslmode=disable")
15 return err
16 }
17
18 func GetDB() (*sql.DB, error) {
19 if db == nil {
20 return nil, errors.New("db hadn‘t open")
21 }
22 return db, nil
23 }
24
25 func dealResult(result sql.Result) error {
26 affect, err := result.RowsAffected()
27 if err != nil {
28 return err
29 }
30 if affect <= 0 {
31 return errors.New("DBExec no affect")
32 }
33 return nil
34 }
35 func ExecSql(Sql string, args ...interface{}) error {
36 stmt, err := db.Prepare(Sql)
37 defer stmt.Close()
38 if err != nil {
39 return err
40 }
41 result, err := stmt.Exec(args...)
42 if err != nil {
43 return err
44 }
45 return dealResult(result)
46 }
47
48 func QuerySql(Sql string, args ...interface{}) (*sql.Rows, error) {
49 stmt, err := db.Prepare(Sql)
50 defer stmt.Close()
51 if err != nil {
52 return nil, err
53 }
54 rows, err := stmt.Query(args...)
55 if err != nil {
56 return nil, err
57 }
58 return rows, err
59 }
60
61 func TxQuerySql(tx *sql.Tx, Sql string, args ...interface{}) (*sql.Stmt, *sql.Rows, error) {
62 stmt, err := tx.Prepare(Sql)
63 if err != nil {
64 return nil, nil, err
65 }
66 rows, err := stmt.Query(args...)
67 if err != nil {
68 return nil, nil, err
69 }
70 return stmt, rows, err
71 }
72
73 func TxExecSql(tx *sql.Tx, Sql string, args ...interface{}) error {
74 stmt, err := tx.Prepare(Sql)
75 defer stmt.Close()
76 if err != nil {
77 return err
78 }
79 result, err := stmt.Exec(args...)
80 if err != nil {
81 return err
82 }
83 return dealResult(result)
84 }
85
86 func ExecMultiSql(Sql string, member []string, args ...interface{}) error {
87 stmt, err := db.Prepare(Sql)
88 if err != nil {
89 return err
90 }
91 for _, val := range member {
92 allArgs := make([]interface{}, 0)
93 allArgs = append(allArgs, val)
94 allArgs = append(allArgs, args...)
95 result, err := stmt.Exec(allArgs...)
96 if err != nil {
97 return err
98 }
99 err = dealResult(result)
100 if err != nil {
101 return err
102 }
103 }
104 return nil
105 }
106
107 func TxExecMultiSql(tx *sql.Tx, Sql string, member []string, args ...interface{}) error {
108 stmt, err := tx.Prepare(Sql)
109 defer stmt.Close()
110 if err != nil {
111 return err
112 }
113 for _, val := range member {
114 allArgs := make([]interface{}, 0)
115 allArgs = append(allArgs, val)
116 allArgs = append(allArgs, args...)
117 result, err := stmt.Exec(allArgs...)
118 if err != nil {
119 return err
120 }
121 err = dealResult(result)
122 if err != nil {
123 return err
124 }
125 }
126 return nil
127 }
MyDB
Go self-sealed PostgreSQL Action Pack