OK thanks everybody!
I thought about it and decided to connect once, do my stuff in the db and disconnect. But, now only my first query completes and I don't understand what is wrong. I have had a few beers now but I don't think that is the problem! My functions are like below. I did not write all variables for the db connection etc.
Code:
int connectodb() {
conn = mysql_init (NULL);
if (conn == NULL){
return 1;
}else{
if (mysql_real_connect (
conn, /* pointer to connection handler */
def_host_name, /* host to connect to */
def_user_name, /* user name */
def_password, /* password */
def_db_name, /* database to use */
0, /* port (use default) */
NULL, /* socket (use default) */
0) /* flags (none) */
== NULL)
{
return 1;
}else{
return 0;
}
}
}
int queryOneRecord(char *qstring) {
if(mysql_query(conn, qstring) == 0) {
res = mysql_use_result(conn);
if ((row = mysql_fetch_row(res)) != NULL) {
dbresult = malloc(strlen(row[0]));
strcpy(dbresult,row[0]);
return 0;
} else {
return 1;
}
} else {
return 1;
}
}
If I have the following in main(), the second query prints no result.
Code:
int main()
{
char *dbresult;
char *sql_query;
char query[1024];
int idnr = 2;
if(connectodb() ==0) {
sql_query = "SELECT employeenr FROM employees WHERE id = %d";
sprintf(query, sql_query, idnr);
if(queryOneRecord(query) == 0 || dbresult != "") {
printf("%s\n",dbresult);
free(dbresult);
}
sql_query = "SELECT employeenr FROM employees WHERE id = %d";
sprintf(query, sql_query, idnr);
if(queryOneRecord(query) == 0 || dbresult != "") {
printf("%s\n",dbresult);
free(dbresult);
}
mysql_close(conn);
}
return 0;
}
If I close the connection and open it again between those queries, they both print results! Why?