Run Queries

Getting data from your schema is essential, and relatively easy to do. After running a query, save your data and then act on it. In the example below, we’re assuming we have a table called options with a row id, an option name (text) and an option value (text):

MySQL Server API

The MySQL server API provides you with a set of tools to connect to and work with MySQL server instances. This includes basic connections, disconnections, querying the instance for databases/tables, and running queries (which is actually a light wrapper for the full Statements API). Results returned, however, are handled and manipulated with the Results API. Statements also have a Statements API that lets you work with statements in much more detail than simply running queries though the main MySQL class.

init

public init()

Creates an instance of the MySQL class that allows you to interact with MySQL databases.

NOTE for ⚠️Character Encoding⚠️

If your dataset contains non-ascii characters, please set this option for proper encoding:

setOption(.MYSQL_SET_CHARSET_NAME, "utf8")

close

public func close()

Closes a connection to MySQL. Most commonly used as a defer after guarding a connection, making sure that your session will close no matter what the outcome.

ping

MySQL connection will go away when idle timeout. The ping() function
can confirm the connectivity and also reconnect if need.

guard mysql.ping() else {
// connection lost
}

clientInfo

public static func clientInfo() -> String

This will give you a string of the MySQL client library version, e.g. "5.7.x" or similar depending on your MySQL installation.

errorCode & errorMessage

public func errorCode() -> UInt32

public func errorMessage() -> String

Error codes and messages are useful when debugging. These functions retrieve, display, and make use of those in Swift. You can learn more about what those mean here. This is especially useful after connecting or running queries. Example:

connect

Opens a connection to the MySQL database when supplied with the bare minimum credentials for your server (usually a host, user, and password). As an option, you can specify the port, database, or socket. Specifying the schema is not required, as you can use the selectDatabase() method after the connection has been made.

selectDatabase

public func selectDatabase(named namd: String) -> Bool

Selects a database from the active MySQL connection.

listTables

public func listTables(wildcard wild: String? = nil) -> [String]

Returns an array of strings representing the different tables available on the selected database.

listDatabases

public func listDatabases(wildcard wild: String? = nil) -> [String]

Returns an array of strings representing the databases available on the MySQL server currently connected.

commit

public func commit() -> Bool

Commits the transaction.

rollback

public func rollback() -> Bool

Rolls back the transaction.

moreResults

public func moreResults() -> Bool

Checks mysql_more_results to see if any more results exist.

nextResult

public func nextResult() -> Int

Returns the next result in a multi-result execution. Most commonly used in a while loop to produce an effect similar to running forEachRow(). For example:

query

public func query(statement stmt: String) -> Bool

Runs an SQL Query given as a string.

storeResults

public func storeResults() -> MySQL.Results?

This retrieves a complete result set from the server and stores it on the client. This should be run after your query and before a function like forEachRow() or next() so that you can ensure that you iterate through all results.

Sets the options for connecting and returns a Boolean for success or failure. Requires a MySQLOpt and has several versions to support setting options that require Booleans, integers, or strings as values.

MySQLOpt values that are available to use are defined by the following enumeration:

MySQL Results API

The results API set provides a set of tools for working with result sets that are obtained from running queries.

close

public func close()

Closes the result set by releasing the results. Make sure you have a close function that is always executed after each session with a connection, otherwise you are going to have some memory problems. This is most commonly found in the defer block, just like in the examples at the top of this page.

dataSeek

public func dataSeek(_ offset: UInt)

Moves to an arbitrary row number in the results given an unsigned integer as an offset.

numRows

public func numRows() -> Int

Lets you know how many rows are in a result set.

numFields

public func numFields() -> Int

Similar to numRows, but returns the number of columns in a result set instead. Very useful for Select * type queries where you may need to know how many columns are in the results.

next

public func next() -> Element?

Returns the next row in the result set as long as one exists.

forEachRow

public func forEachRow(callback: (Element) -> ())

Iterates through all rows in query results. Most useful for appending elements to an array or dictionary, just like we did in the quick start guide.

MySQL Statements API

init

public init(_ mysql: MySQL)

Initializes the MySQL statement structure. This is very commonly used by other API functions to create a statement structure after you’ve passed in a string.

close

public func close()

This frees the MySQL statement structure pointer. Use it or lose valuable memory to the underlying MySQL C API. Most commonly in a defer block, just like we used in quick start.

reset

public func reset()

Resets the statement buffers that are in the server. This doesn’t affect bindings or stored result sets. Learn more about this feature here.

clearBinds

func clearBinds()

Clears the current bindings.

freeResult

public func freeResult(

Releases memory tied up in with the result set produced by execution of a prepared statement. Also closes a cursor if one is open for the statement.

errorCode & errorMessage

public func errorCode() -> UInt32

public func errorMessage() -> String

Error codes and messages are useful when debugging. These functions retrieve, display, and make use of both in Swift. You can learn more about what those mean here. This is especially useful after connecting or running queries. Example: