Skip to content

Instantly share code, notes, and snippets.

@harshitsinghai77
Created November 4, 2020 08:30
Show Gist options
  • Save harshitsinghai77/4c2c0d22f28263de4e72a11185429893 to your computer and use it in GitHub Desktop.
Save harshitsinghai77/4c2c0d22f28263de4e72a11185429893 to your computer and use it in GitHub Desktop.
package dbutils
import (
"database/sql"
"log"
)
// Initialize the database and create required table
func Initialize(dbDriver *sql.DB) {
statement, driverError := dbDriver.Prepare(clubs)
if driverError != nil {
log.Println("driverError ", driverError)
}
// Create player table
_, statementError := statement.Exec()
if statementError != nil {
log.Println("Table already exists!")
}
statement, statementError = dbDriver.Prepare(players)
if statementError != nil {
log.Println("statementError", statementError)
}
statement.Exec()
log.Println("All tables created/initialized successfully!")
}
package dbutils
const clubs = `
CREATE TABLE IF NOT EXISTS clubs (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME VARCHAR(64) NOT NULL,
COUNTRY VARCHAR(64) NOT NULL,
STADIUM VARCHAR(64) NOT NULL,
CreatedAt TIME NULL
)
`
const players = `
CREATE TABLE IF NOT EXISTS players (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME VARCHAR(64) NOT NULL,
ClubID INT,
AGE INTEGER,
POSITION VARCHAR(64) NOT NULL,
CreatedAt TIME NULL,
FOREIGN KEY (ClubID) REFERENCES clubs(ID)
)
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment