-
Notifications
You must be signed in to change notification settings - Fork 0
/
db_connect.go
40 lines (35 loc) · 918 Bytes
/
db_connect.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
package main
import (
"database/sql"
"log"
)
// connectDB establishes a connection to the SQLite database file.
// It opens the database file and creates the users table if it doesn't exist.
// If there is an error opening the database file or creating the table, it logs the error and terminates the program.
// After successfully connecting to the database, it logs a success message.
var db *sql.DB
func ConnectDB() {
// Open the SQLite database file
var err error
db, err = sql.Open("sqlite3", "db_user.db")
if err != nil {
log.Fatal(err)
}
log.Println("Connection to database successful")
// Create the users table if it doesn't exist
createTable := `
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT,
password TEXT
)
`
_, err = db.Exec(createTable)
if err != nil {
log.Fatal(err)
}
err = db.Ping()
if err != nil {
log.Fatal(err)
}
}