Building a SQL in c is painful work. It takes a lot of time to build such thing. I am new to glib. It helps on string manipulation. But I dont find any to shorten query building code. See a sample here.
GString *acc_protocol = g_string_new(acc->prpl->name);
GString *acc_handle = g_string_new(acc->user);
GString *acc_password = g_string_new(acc->pass);
GString *acc_tag = g_string_new(acc->tag);
g_string_printf(q, "INSERT INTO accounts (user, protocol, handle, password, autoconnect, tag) values (%ld, ", user_id);
g_string_append(q,"'");
append_mysql_escaped_param(q, buf, acc_protocol);
g_string_append(q,"', '");
append_mysql_escaped_param(q, buf, acc_handle);
g_string_append(q,"', '");
append_mysql_escaped_param(q, buf, acc_password);
g_string_append(q,"', '");
g_string_append(q, atoi(acc->auto_connect));
g_string_append(q,"', '");
append_mysql_escaped_param(q, buf, acc_tag);
g_string_append(q,"') on duplicate key UPDATE password='");
append_mysql_escaped_param(q, buf, acc_password);
g_string_append(q,"', autoconnect='");
g_string_append(q, atoi(acc->auto_connect));
g_string_append(q,"', tag='");
append_mysql_escaped_param(q, buf, acc_tag);
g_string_append(q,"'");
g_string_free(acc_handle);
g_string_free(acc_password);
g_string_free(acc_protocol);
g_string_free(acc_tag);
mysql_real_query(mysql);
num_rows = mysql_affected_rows(mysql);
....
/// .... mysql processing here ...
For your convenience here is function append_mysql_escaped_param
static void append_mysql_escaped_param(GString *query, GString *buffer, GString *param){
g_string_set_size(buffer, param->len*2+1);
mysql_real_escape_string(mysql, buffer->str, param->str, param->len);
g_string_append(query, buffer->str);
}
How can I make it smaller? There are too many redundant code here which is enough for endless headache. Any idea to improve it?
I know I can use prepared statement. But when I bind the values on prepared statement I need to write such bulk code too. I just want to get rid of redundant code which are error prone. This is true specially for C.