DBCommon.c – Connect to a MySQL database in C

DBCommon.c

MYSQL *do_connect (char *host_name, char *user, char *password, char *db_name)
{
conn = mysql_init(NULL);
if (conn == NULL)
{
print_error(conn, “mysql_init() failedn”);
return (NULL);
}
if (mysql_real_connect(conn, host_name, user, password, db_name, 0, NULL, 0)
== NULL)
{
print_error(conn, “mysql_real_connect() failed”);
return(NULL);
}
return (conn);
}

void print_error(MYSQL *conn, char *message)
{
fprintf(stderr, “%sn”, message);
if (conn != NULL)
fprintf(stderr, “Error %u (%s)n”, mysql_errno(conn), mysql_error(conn));
}

void do_disconnect(MYSQL *conn)
{
mysql_close(conn);
}

DBCommon.h
MYSQL *do_connect(char *h, char *user, char *password, char *db_name);
void print_error(MYSQL *conn, char *msg);
void do_disconnect(MYSQL *conn);