I've created a macOS application to learn and test the local MySQL connections.
I installed MySQL via Homebrew.
I can connect to localhost from my application.
I tried to connect the server while using a non-exist database name, MySQL throws Unknown database 'test'
When I use an existing database name, I get this error:
Unknown prepared statement handler (0) given to mysql_stmt_precheck
My connection code:
import PerfectHTTP
import PerfectHTTPServer
import PerfectMySQL
import Foundation
public class DB {
let host = "127.0.0.1"
let user = "root"
let password = "12345678"
let database = "pets"
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!");
}
}