Home  +  Forums  +  C++ and Sockets  +  C++ and SQL: MySQL, sqlite, ODBC  +  Miscellaneous Projects
Logo
~Database~
~ C++ ~
~Contact~

MySQL wrapped

: another C++ wrapper for the MySQL C API

mysql devconnect member logo
[ About | Download | Examples | Class diagram | License ]

Examples

The following example should be linked with the mysqlclient library from the MySQL distribution / build.

#include <stdio.h>
#include <stdlib.h>
#include <mysql/mysql.h>
#include <string>

#include "Database.h"
#include "Query.h"

int main()
{
	Database db("localhost","dbuser","","testdb");
	Query q(db);

	q.execute("delete from user");
	q.execute("insert into user values(1,'First Person')");
	q.execute("insert into user values(2,'Another Person')");

	q.get_result("select num,name from user");
	while (q.fetch_row())
	{
		long num = q.getval();
		std::string name = q.getstr();

		printf("User#%ld: %s\n", num, name.c_str() );
	}
	q.free_result();
}

Using the embedded MySQL server. The following example should be linked with the mysqld library from the MySQL distribution / build.

#include <stdio.h>
#include <stdlib.h>
#include <mysql/mysql.h>
#include <string>

#include "Database.h"
#include "Query.h"

int main()
{
	// embedded server setup
	const char *server_groups[] = {"test_libmysqld_SERVER","embedded","server",NULL};
	const char *server_argv[] = {
		"main",
		"--datadir=.",
		"--set-variable=key_buffer_size=32M"
	};
	int server_argc = sizeof(server_argv) / sizeof(char *);

	// server init
	mysql_server_init(server_argc, (char **)server_argv, (char **)server_groups);

	// Database instances get their own scope, not one must live when we call
	// mysql_server_end() below
	{
		Database db("testdb"); // Embedded server constructor
		Query q(db);

		q.execute("delete from user");
		q.execute("insert into user values(1,'First Person')");
		q.execute("insert into user values(2,'Another Person')");

		q.get_result("select num,name from user");
		while (q.fetch_row())
		{
			long num = q.getval();
			std::string name = q.getstr();

			printf("User#%ld: %s\n", num, name.c_str() );
		}
		q.free_result();
	} // End of Database scope

	// bring the server down
	mysql_server_end();
}
Page, code, and content Copyright (C) 2021 by Anders Hedström