473,729 Members | 2,235 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(MYSQ L *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_st ring(p, buf, from_len);
}
(void) strcpy(p, "')");
status = mysql_query(con n, 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=loa d_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_co nnect(mysql, server,
user, password, database, 0, NULL, 0))
{
fprintf(stderr, "%s\n", mysql_error(mys ql));
exit(0);
}

/* send SQL query */
if (mysql_real_que ry(mysql, query, strlen(query)))
{
fprintf(stderr, "%s\n", mysql_error(mys ql));
exit(0);
}

// Process the result.
if((res = mysql_store_res ult(mysql)) == NULL)
{
fprintf(stderr, "mysql_store_re sult() failed");
exit(0);
}

while ((row = mysql_fetch_row (res)) != NULL)
{
for (i = 0; i < mysql_num_field s(res); i++)
{
if (i 0)
fputc ('\t', stdout);
printf("%s", row[i] != NULL ? row[i] : "NULL");
}
fputc ('\n', stdout);
}

if (mysql_errno(my sql) != 0)
fprintf(stderr, "mysql_fetch_ro w() failed");
else
printf("%lu rows returned\n", (unsigned long)
mysql_num_rows( res));

/* Release memory used to store results and close connection */
mysql_free_resu lt(res);
mysql_close(mys ql);
}
Nov 4 '06 #1
3 8508
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(MYSQ L *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.comwro te:
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(MYSQ L *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_st ring(p, buf, from_len);
<OT because not related to C but MySQL>
The dicumentation recommends to use myqsl_real_esca pe_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(con n, 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_quer y() 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=loa d_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.comwro te:
<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=loa d_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
9753
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 . "\" into table addresses"; $result = mysql_query($SQL) or die(mysql_error()); The file is located in the same directory as my .PHP file. How do I generate a relative address for this file so that it can be found?
5
1984
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 = mysql_connect( $domain, $user, $password ); I'm using PHP 5.0.1 and MySQL Server: 4.1.9; Client: 5.0.0 Running on Windows XP (IIS, of course)
0
1279
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, searched list archives, the web, etc., and am coming up empty. Somehow, the server is recording the Binary log in the data directory. Each of these log files takes up a gigabyte. This would be all well and good if we were using the server in as a...
0
6685
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 be able to place the PHP file on the server, and I guess you probably can't do that either. Talk about catch 22... The only other way I can think of is to install MySQL on a machine you control, then import the data there using the method I...
0
1691
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 queries. However when using the up arrow to view previously entered SQL statements, the MySQL client throws: Segmentation Fault (core dumped)
0
2082
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 handled. Here is my version: Ver 4.1.5-gamma-log for pc-linux on i686 (Source distribution) Right now I'm trying this to insert binary data: mysql> update table set col=load_file("/path/file") where id=1;
4
6723
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 code ?? thank you Pedro Leite From Portugal ------------------------------------
0
2168
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 from the del file to mysql table, it generate an error. below is the load data infile syntax i use =
3
6003
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 values, transfer those numeric values over ASP.NET. I had no problem doing this on my local computer, by getting the field with "cast(field as BINARY)" so that on ASP.NET I have a byte array.Then send every field of array over ASP.Net.
0
8761
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9200
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9142
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6016
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3238
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2162
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.