Using C++ to create a database

May 15, 2012 at 11:05am
Is there a way I can store some data into a database and write a C++ program that allows users to access that data?
May 15, 2012 at 11:32am
Yes. Many ways, from a simple text file to accessing SQl (and other such) databases.
May 15, 2012 at 12:18pm
i used sqlite in the past... very easy...
May 15, 2012 at 8:49pm
I normally use the MySQL C API and it seems to work just fine for my needs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <mysql.h>
#include <cstdio>

int main()
{
	MYSQL *conn;
	MYSQL_RES *res;
	MYSQL_ROW row;
	char *server = "localhost";
	char *user = "user";
	char *password = "password";
	char *database = "database";
	conn = mysql_init(NULL);
	
	// connect to database
	if(!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0))
	{
		fprintf(stderr, "%s\n", mysql_error(conn));
		return -1;
	}
	
	// send SQL query
	if(mysql_query(conn, "select * from cpp_testTAB"))
	{
		fprintf(stderr, "%s\n", mysql_error(conn));
		return -1;
	}
	
	res = mysql_use_result(conn);
	
	// output table name
	printf("MySQL Tables in mysql database:\n");
	while ((row = mysql_fetch_row(res)) != NULL)
	{
		printf("%s %s %s %s\n", row[0], row[1], row[2], row[3]);
	}
	
	// close connection
	mysql_free_result(res);
	mysql_close(conn);
	
	return 0;
}
/*
 *    To compile in Linux type this in:
 *         g++ -o sqltest $(mysql_config --cflags) mysqltest.cpp $(mysql_config --libs) -Wno-write-strings
 */
Last edited on May 15, 2012 at 8:50pm by closed account z6A9GNh0
Topic archived. No new replies allowed.