To achieve the objective I'm going to make a class to connect and launch SQL queries to the MySql server , and of course a test project to use the class.
So the steps to get started are:
- Open code::blocks
- Create an empty project
- Add a file and save it "main.cpp"
- Add a new class with the wizard and name it "csql"
Basically there are 5 functions: the creator and destructor, a function to connect to the mysql server, a function to execute queries and finally a function to get the result from SELECT queries.
Now the implementation (csql.cpp):
It is quite simple to follow the code:
- csql() (constructor) just initializes the mysql class used to work with the DB
- ~csql() (destructor) frees the class, closing any active connection
- connect() connect to the server, using 4 parameters: the server IP, the username, the password and the database to connect (it returns true if the it connects ok, false when there is a failure)
- executequery() used to launch SQL queries, just plain SQL commands like "select * from table"
- getrow() get a data row from the results of a select query, if there are rows it will return true and we can access the data columns with csql_instance.row[index], other way it returns false
I make an instance from the mysql class, then I connect to the server, clean the table "accounts", and then I insert a pair of data rows, I display the results from select queries too, there are other SQL commands like UPDATE which I have not used, but I think that it is quite enough to show the use from the class.
<Notice that I am using the password "rpgdata", the database "rpgdata", the table "accounts".. if you don't use the same database or table names, the example wont work(I explained how to set it up in the previous two posts)>
Finally there is one final thing you need to set up to make the project compile:
- Go to "project" > "build options"
- Then in "compiler" > "other options"
- And in "linker" > "other linker options"
Other way the compiler wont find mysql and it will refuse to work...
<So basically we have a simple class to use the freshly new installed MySql server, now we can use it in any project, but obviously I'm going to add it to the socket server, in the next post I will show another new I'm going to use to host the project development...>