MySQL Tutorial (Neko)

There is several API already provided with Haxe. One of the useful ones enables you to access MySQL databases very easily.

Connection to the Database
The first step is to connect to the database. Here's a sample that shows how to establish a connection:

This will establish a connection on localhost:3306 with user root and empty password. You can also use a socket on Unix systems to connect to the database. If you want to connect using the standard way, set socket to null.

Once the connection is established, a /api/neko/db/Connection object is returned. You can use it to select the database on which you want to operate.

After you're done with using the connection, you can simply close it.

Request and Result
You can execute a request using the cnx.request("QUERY") method. This will return a /api/neko/db/ResultSet containing all the rows. Here's an example :

If the field you select does not have a name, you can use the get methods from the result set :

In the case of an "INSERT", UPDATE or "DELETE" request, the length with tell the number of rows affected* :

(*) This similar to php's mysql_affected_rows

Type Conversions
When you execute a request, the rows in the ResultSet are anonymous objects containing table values. The MySQL types are automaticaly converted to the corresponding Haxe types :

(*) : can contain \0 character

Escaping
If you want to use Strings inside your SQL requests, don't forget to escape them so they can't be forged to execute additional SQL. For example :

Or by using the quote method :

Possible problems

 * Error: **Exception : Neko_error(mysql.c(438) : Failed to connect to mysql server : Client does not support authentication protocol requested by server; consider upgrading MySQL client)


 * Cause: **MySQL 4.1 and up uses an authentication protocol based on a password hashing algorithm that is incompatible with older clients.


 * Solution: **Run mysql and login as root.

Then update your mysql user (change somepassword, someuser, somehost as needed)

See
See the following API references pages :

* /api/neko/db/Mysql * /api/neko/db/Connection * /api/neko/db/ResultSet

You can also read the /doc/neko/spod Tutorial for a more highlevel API.