Chapter 8. Accessing Databases
Storing and accessing data.
Storing and accessing data in a database is an important part of programming. This is something which is often used in web and other developments.
When developing an application, whether it is a web application, a desktop application, or even a mobile application, we are dealing with a lot of data. Indeed, that's mostly why applications are around—dealing with data.
Using databases can help to make it easier to deal with data. They may help store and retrieve data, and moreover, they can help filter the data you are going to retrieve.
In this chapter, we will:
Learn how to connect to MySQL databases
Learn how to connect to SQLite databases
See how to query databases
See how to map haXe objects to databases
So now, if you're ready, let's go!
haXe offers you two connectors in its standard library. Those two connectors can be used when targeting the PHP or Neko platforms.
Unfortunately, at the time of writing, the standard library does not provide any way to connect to databases when targeting C++.
So, on PHP and Neko, you will be able to connect to MySQL and SQLite databases. Note that these two databases systems work by following two different schemes:
MySQL is based on a client/server model where your application is the client and connects to the server using a login and a password.
SQLite databases are stored in a file on your filesystem. Therefore, you will have to make sure that your user has the correct access rights on the file storing your database. SQLite databases are really good when you don't want to depend on installing and running a server. This is particularly interesting when you want to create some locally running applications.
php.db.Connection and neko.db.Connection
Whether we connect to a...
SPOD stands for Simple Persistence Objects Database. It is a functionality of the library to allow one to define objects in haXe and save and retrieve them easily from a database.
In fact, you will need to map haXe classes to tables in your database and you will be able to insert new records, delete them, update them, and search them.
To create objects that you will be able to use as SPOD objects, you have to create a class that extends neko.db.Object
or php.db.Object
.
Simply create the fields that exist in your table in the class as you would normally do:
We will also need to define a manager
; it will be in charge of managing many operations for objects of this type. There is a standard one that you can use:
A concrete example of SPOD use
Let's see a concrete example of how to use that.
Set up a database in your MySQL server with a table named Users
.
In this table, add the following three fields:
id
: This should be the Primary Key and have auto_increment
, so that we don't have to worry about generating the Primary Keys.
username
: This should be a text; we will use it to store the user's username.
password
: This should be a text too; we will use it to store the user's password hash.
Now, let's create a User
class reflecting those fields and useable as SPOD:
Note
Note: We are going to use the standard Manager
.
Remember how we named our table Users
and see how our class is named User
? This makes perfect sense and it respects/accounts for what people are used to seeing. Still, we will need...
We have already seen how to initialize the manager
, now, let's have a quick look at what it has to offer.
This function returns a list of all records present in the table. It takes an optional lock parameter that, if true, indicates that records that are going to be retrieved should have a lock put on them.
This function allows you to get the number of records that are present in the table. It can take an optional anonymous object as a parameter in order to filter records. By doing this, you can, for example, pass this object {sex : "M"}
if you want to get only records corresponding to a male person.
The delete
function allows you to delete objects. Just like the count
function, it can take an anonymous object to filter records that will be concerned.
The get
function is certainly one of the most important functions; it allows you to retrieve an object from the database based on its Primary Key. It can also get...
Most of the time, you have modeled your database with relations inside it.
The haXe SPOD is able to handle one-to-one and many-to-one relations.
This is done by implementing the static function RELATIONS
that takes no parameter. It has to return an array of anonymous objects made of the fields prop
, key
, and manager
.
The prop
field will be a string that is the name of a property by which you will get and set the object. This property has to be a dynamic property.
The key
field is also a string that is the name of the field (in the database) that stores the foreign key.
So, let's take our User
example and a sponsorship program to it. A user can sponsor another one.
Creating a blogging system
Now that we have seen how we can query databases and how we can use the SPOD system, we are going to try implementing something that looks like a very simple blogging system.
We will have the following four functionalities:
Adding a new post.
Listing posts.
Adding a user.
Listing users.
In order to choose what actions we want to execute, we will use the GET
parameter "action". We will also pass other parameters needed by the action through GET
parameters.
Time for action – Creating the Users table
Firstly, we are going to create a table named Users
which will hold information about users. We will need the following three fields:
username
: Will hold the user's login.
password
: Will hold the user's password hashed.
id
: The Primary Key.
The following is the SQL query you can use to create this table:
This will create the table and the ID will also have auto_increment
set on it.
Time for action – Creating the User class
Now, we will create the User
class that maps to the Users
table as follows:
There are several things to note here:
We are redefining the table to use by setting the TABLE_NAME
static variable to Users
We have created a simple function to set the password to the hash of the password
We are performing some imports depending on the platform, so that our application can run in both Neko and PHP
Time for action – Creating the Posts table
We will now create a table named Posts
which will hold all our blog posts.
This table will have the following five fields:
id
: The ID of the post
title
: The post's title
body
: The post's text
fk_author
: This will contain the ID of the author
postedOn
: The date when the post was published
The following is the SQL query that you can use to create this table:
Our table will be set correctly with this query.
Time for action – Creating the Post class
We will now create the Post
class mapping to the Posts
table.
We will need to redefine the table it is mapped to.
We will also need to define its relation to the User table.
As you can see, we have our imports at the top of the class to ensure that this will work on Neko and PHP.
We also have the fk_author
field definition and most importantly, we have...
Time for action – Creating the connection to the database
For our main
function, we are going to do it systematically.
At first, let's create the connection to the database:
Time for action – Listing posts
Now, let's create a function to list posts. This one is pretty easy:
As you can see, it simply prints information from every post.
Also, note that you can use the User
object corresponding to the author
directly. This is one of the most interesting parts of the SPOD system.
Therefore, our main
class now looks like this:
Time for action – Listing users
Now, we are going to create a function to list all users.
This one is even simpler than listing posts because it has no relations.
Our class now looks like the following:
Time for action – Adding a user
Now, let's create the function to add a user. It will take the login and the password as parameters and will return the created object as follows:
Time for action – Adding a post
The function to create a post will have a little twist because it will have to set the author of the post. It will take, among other information, the name of the author. We will then retrieve the author's object by using the manager's search function.
Time for action – Branching it with the main function
Now, let's just add some code to act depending on the action GET
parameters and get all parameters as needed by the action and pass them to our functions:
Therefore, our complete class is as follows:
So, in this chapter, we have learned quite a lot of things about how to manipulate data from databases with haXe.
Specifically, we covered how to connect to MySQL and SQLite databases, how to query those databases with the low-level API, and how to use the SPOD library in order to store, retrieve, modify, and delete objects from the database.
Now that we know how to use databases, we will learn how we can do some templating. That may prove to be useful to display our objects in a more elegant way. So, are you ready? Let's go on!