Last active
December 2, 2017 22:11
-
-
Save kidcodely/2cb68d4732b79fc3f3a4b17faadb63bc to your computer and use it in GitHub Desktop.
Database class for server side swift project
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import PerfectHTTP | |
import PerfectHTTPServer | |
import PerfectMySQL | |
import Foundation | |
public class DB { | |
// You'll need to update these values based on how you've set up MySQL. | |
let host = "127.0.0.1" | |
let user = "root" | |
let password = "admin" | |
let database = "nintendo" | |
func databaseConnect(host: String, user: String, password: String, db: String) -> MySQL { | |
let mysql = MySQL() // Create an instance of MySQL to work with | |
let connected = mysql.connect(host: host, user: user, password: password, db: db) | |
guard connected else { | |
// verify that we have connected successfully | |
print(mysql.errorMessage()) | |
return mysql | |
} | |
return mysql | |
} | |
public func insertGame(title: String, description: String, createdDate: String){ | |
// Connect to our database | |
var db = databaseConnect(host: host, user: user, password: password, db: database) | |
defer { | |
db.close() //This defer block makes sure we terminate the connection once finished, regardless of the result | |
} | |
// Create the statement we wish to execute | |
let statement = MySQLStmt(db) | |
let insert = "INSERT INTO game(id, title, description, release_date) VALUES (\(statement.insertId()), '\(title)', '\(description)', '\(createdDate)');" | |
_ = statement.prepare(statement: insert) | |
// Run the query | |
let querySuccess = statement.execute() | |
// Check that our query was successfuly, otherwise return out | |
guard querySuccess else { | |
print(db.errorMessage()) | |
return | |
} | |
print("Insert successful!"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment