intelliproject logo

Location: Desktop development - C/C++    License: The Intelliproject Open License (IPOL)

Accessing a MySQL Database from C++

Posted by Silviu Caragea

A wrapper class that can be useful when you want to connect to a MySQL database from C + +

Skill: Intermediate

Posted: 03/10/2008

Views: 1580

Rating: 5.00 /5

Popularity: 0.00

Sign Up to vote for this article

Introduction

MySQL provide C libraries that enable the creation of MySQL database applications.
In this article I will present a simple class that encapsulates the functionality of MySQL database access commands.

It establishes database connections, executes queries, storing the result  and provides other functions to traverse the result set an retrieve the data returned by the database server.

Mysql C++ wrapper

This class contains the most used MySql methods.

BOOL OpenConnection(char* host,char *username,char *password);

Attempts to establish a connection to a MySQL database engine running on host. OpenConnection must complete successfully before you can execute any other API functions that require a valid MYSQL connection handle structure.

BOOL SelectDatabase(char* dbf);

Causes the database specified by dbf to become the default (current) database on the connection specified by MYSQL* myData;.SelectDatabase fails unless the connected user can be authenticated as having permission to use the database.

BOOL CreateDataBase(char* name);

Creates the database named by the name parameter. This function is deprecated. It is preferable to use DoQuery()  to issue an SQL CREATE DATABASE statement instead.

BOOL DropDataBase(char* nume);

Drops the database named by the db parameter. This function is deprecated. It is preferable to use DoQuery() to issue an SQL DROP DATABASE statement instead.

BOOL DoQuery(char*szSQL);

Executes the SQL statement pointed to by the null-terminated string szSQL.  Normally, the string must consist of a single SQL statement and you should not add a terminating semicolon (“;”) or \g to the statement. If multiple-statement execution has been enabled, the string can contain several statements separated by semicolons. DoQuery() cannot be  used for statements that contain binary data; you must use encapsulate  mysql_real_query() instead in another class method. (Binary data may contain the “\0” character, which mysql_query() used by DoQuery interprets as the end of the statement string.)

MYSQL_RES * GetQueryResult();

Reads the entire result of a query to the client, allocates a MYSQL_RES structure, and places the result into this structure. GetQueryResult() returns a null pointer if the statement didn't return a result set (for example, if it was an INSERT statement).

void FreeQueryResult(MYSQL_RES *result);   

Frees the memory allocated for a result set for example by GetQueryResult. When you are done with a result set, you must free the memory it uses by calling FreeQueryResult. Do not attempt to access a result set after freeing it.

MYSQL_ROW MySQLFetchResult(MYSQL_RES *result);

Retrieves the next row of a result set. When used after GetQueryResult(), MySQLFetchResult() returns NULL when there are no more rows to retrieve or if an error occurred.

LONG GetQueryRowsNumber(MYSQL_RES *result);  

Returns the number of rows in the result set.  GetQueryRowsNumber() is intended for use with statements that return a result set, such as SELECT. For statements such as INSERT, UPDATE, or DELETE, the number of affected rows can be obtained with GetMysqlAffectedRows().

LONG GetMysqlAffectedRows();

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records were updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error.

LONG GetLastInsertID();

Returns the value generated for an AUTO_INCREMENT column by the previous INSERT or UPDATE statement. Use this function after you have performed an INSERT statement into a table that contains an AUTO_INCREMENT field, or have used INSERT or UPDATE to set a column value with LAST_INSERT_ID(expr).

char* GetMySqlError();

For the connection specified by MYSQL* myData;  GetMySqlError() returns a null-terminated string containing the error message for the most recently invoked API function that failed. If a function didn't fail, the return value of GetMySqlError() may be the previous error or an empty string to indicate no error.

void CloseConection();

Closes a previously opened connection.  CloseConection () also deallocates the connection handle if the handle was allocated automatically by OpenConnection.This function is called automatically in class destructor.

How to use this code

If you want to see how to use this MySql wrapper class download the sources . I tried to make an easy example that uses almost all class methods.

License

This article, along with any associated source code and files, is licensed under The Intelliproject Open License (IPOL)

About the author

Silviu Caragea

Silviu Caragea is the Founder, Administrator and Chief Editor who wrote and runs The IntelliProject.

He's been programming since 2000 and now he's student at The Faculty of Economic Cybernetics, Statistics and Informatics from Bucharest. In the same time he's working as software developer at Cratima Software, a Romanian software and web design company that activates both on the local and foreign market, providing its customers with software development services, internet and intranet solutions, web design, graphic design and IT consultancy.

His programming experience includes:
- C,C++, Visual C++(Win32 API, MFC, ADO, STL, DAO, ODBC, ATL, COM, DirectShow, DirectDraw, WTL)
- Open Source libraries :CURL & Boost
- HTML, CSS
- Java (SE,ME)
- JavaScript, Ajax, Google Web Toolkit (GWT)
- Php, MySQL
-Oracle, PL SQL
- C# .NET
-Objective C, IPhone SDK, Cocoa

Location: Romania
Ocupation: Software Engineer
Home page: http://www.intelliproject.net

Posted by Alex Snet at 03/10/2009 04:34
Does it work on *nix/Mac?
Is it a crossplatform package?
Posted by Silviu Caragea at 04/10/2009 13:45
You can use this wrapper on Mac , but you must make some little changes..(for example on Mac you don't have BOOL or LONG they are defined as bool , long) ..

Sign up to post message on the article message board!