Jump to content

MySQL C API


Recommended Posts

Well, I learned how to use mysql in C a while ago, but I never really tried to actually use it.  I had a strange urge to try it, and this is what I came up with:

 

#include <my_global.h>
#include <my_sys.h>
#include <mysql.h>
#include "utils.h"

char *opt_host_name = NULL;
char *opt_user_name = NULL;
char *opt_password = NULL;
unsigned int opt_port_num = 0;
char *opt_socket_name = NULL;
char *opt_db_name = NULL;
unsigned int opt_flags = 0;

static MYSQL *conn;

int
main (int argc, char **argv)
{
conn = mysql_init(NULL);
if (conn == NULL) {
	fprintf(stderr, "mysql_init() failed!\n");
	exit(1);
}

if (mysql_real_connect(conn, opt_host_name, opt_user_name, opt_password, opt_db_name, opt_port_num, opt_socket_name, opt_flags) == NULL) {
	fprintf(stderr, "mysql connection failed!\n");
	exit(1);
}

MYSQL_RES *result;
if (mysql_query(conn, "SELECT username FROM users") != 0)
	sql_error_print(conn, "Friend query failed");
else {
	result = mysql_store_result(conn);
	if (result == NULL)
		sql_error_print(conn, "Result store failed");
	else {
		sql_process_row(conn, result);	
		/* Free the result! */	
		mysql_free_result(result);	
	}
}

/*Disconnect so we don't leak memory*/
mysql_close(conn);
exit(0);
}

 

It works fine, but I wanted to know if anyone saw anything I should fix.  The utils.h file defines sql_error_print() and sql_process_row(), and they're just utility functions I wrote to keep from having a bunch of MYSQL_ROW pointers and to neaten up my code. ;)

 

Btw, I have real connection details in my script, but I decided to just NULL them out here.  And I know how to get the connection options from a config file or the command line, but I wanted to keep it simple for now.

Link to comment
https://forums.phpfreaks.com/topic/130947-mysql-c-api/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.