wiki:Docs/Prog/Manual/ApplicationLibraries/Database/MySQLclient

Version 4 (modified by Don Wilson, 12 years ago) ( diff )

--

MySQL Client

Example:

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

int main(int argc, char* argv[])
{
	MYSQL* conn;
	MYSQL_RES* res;
	MYSQL_ROW row;

	const char* server = "192.168.1.106";
	const char* user = "pi";
	const char* password = "raspberry";
	const char* database = "test";
	const char* query = "SELECT * FROM abc;";

	if(argc > 1)
		server = argv[1];
	if(argc > 2)
		user = argv[2];
	if(argc > 3)
		password = argv[3];
	if(argc > 4)
		database = argv[4];
	if(argc > 5)
		query = argv[5];

	printf("**srv [%s] user [%s] pass [%s] db [%s] q [%s]\n", server, user, password, database, query);

	conn = mysql_init(NULL);

	if(!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0))
	{
		printf("Error connecting to DB: %s\n", mysql_error(conn));
		return 0;
	}

	printf("***\n");

	if(mysql_query(conn, query))
	{
		printf("Error query: %s\n", mysql_error(conn));
		return 0;
	}

	//printf("query success\n");

	int rows_affected = (int) mysql_affected_rows(conn);

	printf("affected %d\n", rows_affected);

	if(rows_affected < 1) // select, show
	{
		res = mysql_use_result(conn);
		//printf("rows %d filuelds %d eof %d\n", res->row_count, res->field_count, res->eof);

		int cnt = 0, i;

		while((row = mysql_fetch_row(res)) != NULL)
		{
			cnt++;
			if(cnt == 1)
			{
				for(i = 0; i < (int)res->field_count; i++)
				{

				    if(i > 50)
				    	break;
					printf("%s,", res->fields[i].name);
				}
				printf("\n");

			}
			if(cnt > 10000)
				break;
			//printf("%d ", cnt);
			for(i = 0; i < (int)res->field_count; i++)
			{

			    if(i > 50)
			    	break;
				printf("%s,", row[i]);
			}
			printf("\n");
		}
		mysql_free_result(res);
	}
	mysql_close(conn);

	return 0;
}

Attachments (2)

Download all attachments as: .zip

Note: See TracWiki for help on using the wiki.