Skip to content

Commit f19490b

Browse files
committed
Keep Database connection online
1 parent d4819bd commit f19490b

File tree

2 files changed

+7
-6
lines changed

2 files changed

+7
-6
lines changed

internal/database/database.go

+6-6
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,19 @@ import (
88
"github.com/steveyiyo/url-shortener/internal/tools"
99
)
1010

11+
var db *sql.DB
12+
13+
func Init() {
14+
db, _ = sql.Open("sqlite3", "./data.db")
15+
}
16+
1117
// Create file and table
1218
func CreateTable() {
1319
// Create Table
14-
db, err := sql.Open("sqlite3", "./data.db")
15-
tools.ErrCheck(err)
1620
stmt, err := db.Prepare("CREATE TABLE IF NOT EXISTS urlinfo (ShortID string, Link string, Expireat string);")
1721
tools.ErrCheck(err)
1822
stmt.Exec()
1923
tools.ErrCheck(err)
20-
db.Close()
2124
}
2225

2326
// Add data to DB
@@ -29,13 +32,10 @@ func AddData(ShortID string, Link string, ExpireAt int64) {
2932
res, err := stmt.Exec(ShortID, Link, ExpireAt)
3033
tools.ErrCheck(err)
3134
res.LastInsertId()
32-
db.Close()
3335
}
3436

3537
// Get data from DB
3638
func QueryData(ID string) (bool, string) {
37-
db, err := sql.Open("sqlite3", "./data.db")
38-
tools.ErrCheck(err)
3939
now := time.Now().Unix()
4040
rows, err := db.Query("SELECT * FROM urlinfo WHERE ShortID = ?", ID)
4141
tools.ErrCheck(err)

main.go

+1
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ func main() {
141141
cache.InitRedis()
142142

143143
// Init Database
144+
database.Init()
144145
database.CreateTable()
145146

146147
// Init Web Server

0 commit comments

Comments
 (0)