473,419 Members | 1,842 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,419 software developers and data experts.

C client to load binary data to MySQL

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);
}
Nov 4 '06 #1
3 8458
Me Alone wrote:
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;
These 110K of data may be too big for your environment's stack.

Otherwise, where exactly does the fault occur?

--
Ian Collins.
Nov 4 '06 #2
Me Alone <me@home.comwrote:
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?
#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");
Shouldn't you return, indicating failure, when opening the file fails?
If it failed you will be passing a NULL pointer to fread(). That might
result in a crash.
sprintf(query, "INSERT INTO images VALUES (%d,'", 300);
Why not simply use

strcpy( query, "INSERT INTO images VALUES (300,'");

That should do exactly the same.
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))
From a nit-picky point of view this is not 100% correct - according
to the C standard you're only allowed to compare pointers pointing
witin the same object. But in case 'p + 2 * from_len + 3' is too
large this expression already points outside of 'query'. In order
not to violate this constraint you would need to e.g. use a counter
of how much you already have used of 'query' and compare to that.
But I don't think that this is the real problem..
{
fprintf(stderr, "image too big");
return(1);
}
p += mysql_escape_string(p, buf, from_len);
<OT because not related to C but MySQL>
The dicumentation recommends to use myqsl_real_escape_string() instead.
</OT>
}
(void) strcpy(p, "')");
Unless you want to use lint or a similar tool te '(void)' bit at the
start of the line is superfluous.
status = mysql_query(conn, query);
This, of course, assumes that 'conn' is a pointer to an open connection
to the database. I don't know what will happen if you pass it an invalid
pointer, one thing that could happen is a crash...

<OT>
The MySQL documentation explicitely states:
mysql_query() cannot be used for queries that contain binary data; you
should use mysql_real_query() instead. (Binary data may contain the \0
character, which mysql_query() interprets as the end of the query string.)
You should take that into consideration since it's rather likeley that
what's in a .gif file is binary data.
</OT>
return(status);
}
main() {
main() is suposed to return an int. And since you don't pass it arguments
make that

int main(void) {
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);
And here's definitely a problem: you call your function for putting
the image into the database (load_image() seems to be a mis-nomer for
what the function does) before you ever opened a connection to it.
Depending on how mysql_query() handles that case (it probably can't
since 'mysql' contains some garbage data, not even necessarily NULL
which it could check for) that might be the most likely reason for
the segmentation fault.
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\__________________________ http://toerring.de
Nov 4 '06 #3
Jens Thoms Toerring wrote:
Me Alone <me@home.comwrote:
<snip>
That should do exactly the same.
> 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))

From a nit-picky point of view this is not 100% correct - according
to the C standard you're only allowed to compare pointers pointing
witin the same object. But in case 'p + 2 * from_len + 3' is too
large this expression already points outside of 'query'.
However, by applying a little algebra we can get a test that does not
have this problem. Subtract query from both sides of the expression and
we get:
if ((p - query) + (2*from_len) + 3 sizeof(query))

This is valid on any implementation as long as both pointers are in to
the same object, the difference between them can be represented and we
don't have anything else causing an arithmetic overflow. Since one is
unlikely to be constructing a query string anywhere even close to 30000
characters long I would say this makes it safe for all implementations
without being any harder to read.
In order
not to violate this constraint you would need to e.g. use a counter
of how much you already have used of 'query' and compare to that.
But I don't think that this is the real problem..
I agree with you. However I don't see any good reason to leave this
unfixed seeing as the fix is so simple.

<snip>
> if ((fromImage=load_image(mysql)) 0)
fprintf(stderr, "%d", fromImage);

And here's definitely a problem: you call your function for putting
the image into the database (load_image() seems to be a mis-nomer for
<snip>

To the OP, if you need further help with the MySQL parts of this, such
as the load_image function and connecting to the database, please take
it to a suitable group, possibly one with mysql or database in its name,
or the MySQL mailing lists. This group is for discussing C, not the
myriads of third party libraries which have their own groups and mailing
lists.
--
Flash Gordon
Nov 4 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: Bruce A. Julseth | last post by:
When I execute this SQL statement in my PHP code, I get an error "File '.\Address.txt' not found (Errcode: 2)" $File = addslashes(".\Address.txt"); $SQL = "Load Data InFile \"" . $File . "\"...
5
by: Martin | last post by:
I don't know if this is a PHP problem or a MySQL problem - hopefully, someone here can give me a clue. I am getting the subject error when I try to connect to MySQL from a PHP page. $conn =...
0
by: Turtle | last post by:
We've been using MySQLD for a few years now quite happily. It's amazing how well it performs. However, I have a minor issue, and I'm not sure how to deal with it. I've scoured the manual,...
0
by: Donald Tyler | last post by:
Then the only way you can do it that I can think of is to write a PHP script to do basically what PHPMyAdmin is trying to do but without the LOCAL in there. However to do that you would need to...
0
by: Robert Mazur | last post by:
Solaris 9 - sparc 64bit MySQL 5.0 alpha (installed using binary from MySQL) --------------------------------- Has anyone expereinced this? The client will launch locally and process SQL...
0
by: David List | last post by:
I am wondering what I miss to be able to handle binary data from the mysql client. I have ensured that the user has file_priv set to 'Y' and that max_allowed_packet is larger that the binary lumps...
4
by: Pedro Leite | last post by:
Good Afternoon. the code below is properly retreiving binary data from a database and saving it. but instead of saving at client machine is saving at the server machine. what is wrong with my...
0
by: lanesbalik | last post by:
hi all, right now i'm trying to migrate from db2 running under linux to mysql v5.1. i manage to export out the db2 structure & data into a del (ascii) file. but when i try to load the data...
3
by: ist | last post by:
Hi, I am trying to get (and transfer over ASP.NET) some encrypted data from some MySQL fields. Since the data contains many unicode characters, I tried to get the data as a series of ASCII...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.