Skip to content

Instantly share code, notes, and snippets.

@kidcodely
Last active December 2, 2017 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kidcodely/2cb68d4732b79fc3f3a4b17faadb63bc to your computer and use it in GitHub Desktop.
Save kidcodely/2cb68d4732b79fc3f3a4b17faadb63bc to your computer and use it in GitHub Desktop.
Database class for server side swift project
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