Creating a basic C/C++ Program to Interact with MySQL and MariaDB

In this post, I’ll cover how to create a simple C/C++ program that interacts with MySQL using the C API (and Connector/C). I discussed in a previous post how to install the C Connector (both SkySQL and MySQL’s), so please refer to that if you are looking for more specifics on that.

So once you have that set up, then there are just a few more things you need to have in order – at least this was the case in my environment.

1. Create a program (this one simply connects to the server and retrieves the server version):

#include <stdio.h>
#include <windows.h>
#include <mysql.h>

MYSQL *conn;
int version = 1;

int main ( int argc, char *argv[] )
{
    conn = mysql_init ( NULL );
    mysql_real_connect ( conn, "localhost", "root",
            "password", "test", 3308, NULL, 0 );
	version = mysql_get_server_version( conn );
	printf("\nMySQL Version = %d\n",version);
    mysql_close ( conn );
    return 0;
}

I saved it as c:\chris\mysql1\mysql1.c.

2. I copied libmysql.dll and libmysql.lib to c:\chris\mysql1
     (There’s probably a better way than this, but this works for now.)

3. cd c:\chris\mysql1\

4. Compile your program (I’m compiling from the command line, using cl.exe):

cl /I "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include"
/I "C:\Program Files (x86)\MySQL\mysql-5.5.30-win32\include"
/I "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Include"
/MD "C:\Program Files (x86)\MySQL\mysql-5.5.30-win32\lib\libmysql.lib"
mysql1.c

You need the various includes specified by the /I, and the /MD indicates we’re compiling it dynamically (as opposed to statically – /MT).

5. Run Program, by just typing the name (from the same location) – “mysql1″ in this case:

mysql1

Here is the full session output:

c:\chris\mysql1>
cl /I "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include"
/I "C:\Program Files (x86)\MySQL\mysql-5.5.30-win32\include"
/I "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Include"
/MD "C:\Program Files (x86)\MySQL\mysql-5.5.30-win32\lib\libmysql.lib"
mysql1.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version
16.00.30319.01 for 80x86
Copyright (C) Microsoft Corporation.  All rights reserved.

mysql1.c
Microsoft (R) Incremental Linker Version 10.00.30319.01
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:mysql1.exe
"C:\Program Files (x86)\MySQL\mysql-5.5.30-win32\lib\libmysql.lib"
mysql1.obj

c:\chris\mysql1>mysql1

MySQL Version = 50532

c:\chris\mysql1>

Fwiw, I did run into a number of errors, but I’ve posted that in a follow-up, so as to keep this post more focused.

Hope this helps.

 

Tags: , , , , , , , , , , ,

Comments are closed.


Period Panties by Period Panteez Menstrual Underwear Menstruation PMS Panty