Hello:
I am trying to edit some C code I found in "The definitive guide to
using, programming, and administering MySQL" by Paul DuBois. This C
client program connects and then segfaults when the function load_image
is called. Would anyone be able to point me to what I might be doing
wrong?
Thanks in advance,
C Newbie
#include <mysql/mysql.h>
#include <stdio.h>
int load_image(MYSQL *conn)
{
FILE * pic;
char query[1024*100], buf[1024*10], *p;
unsigned int from_len;
int status;
if ((pic = fopen("./oreilly.gif", "r")) != NULL)
{
printf("Open command succeeded\n");
}
else
printf("Open command failed.\n");
sprintf(query, "INSERT INTO images VALUES (%d,'", 300);
p = query + strlen(query);
while ((from_len = fread(buf, 1, sizeof(buf), pic)) 0)
{
/* don't overrun end of query buffer! */
if (p + (2*from_len) + 3 query + sizeof(query))
{
fprintf(stderr, "image too big");
return(1);
}
p += mysql_escape_string(p, buf, from_len);
}
(void) strcpy(p, "')");
status = mysql_query(conn, query);
return(status);
}
main() {
MYSQL * mysql;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "user";
char *password = "password";
char *database = "db";
unsigned int i;
char * query = "SELECT * FROM table";
int fromImage;
if ((fromImage=load_image(mysql)) 0)
fprintf(stderr, "%d", fromImage);
if((mysql = mysql_init(NULL)) == NULL)
{
fprintf(stderr, "Cannot initialize MySQL");
exit(1);
}
/* Connect to database */
if (!mysql_real_connect(mysql, server,
user, password, database, 0, NULL, 0))
{
fprintf(stderr, "%s\n", mysql_error(mysql));
exit(0);
}
/* send SQL query */
if (mysql_real_query(mysql, query, strlen(query)))
{
fprintf(stderr, "%s\n", mysql_error(mysql));
exit(0);
}
// Process the result.
if((res = mysql_store_result(mysql)) == NULL)
{
fprintf(stderr, "mysql_store_result() failed");
exit(0);
}
while ((row = mysql_fetch_row(res)) != NULL)
{
for (i = 0; i < mysql_num_fields(res); i++)
{
if (i 0)
fputc ('\t', stdout);
printf("%s", row[i] != NULL ? row[i] : "NULL");
}
fputc ('\n', stdout);
}
if (mysql_errno(mysql) != 0)
fprintf(stderr, "mysql_fetch_row() failed");
else
printf("%lu rows returned\n", (unsigned long)
mysql_num_rows(res));
/* Release memory used to store results and close connection */
mysql_free_result(res);
mysql_close(mysql);
}