Adding Images to MySQL

Victor Subervi victorsubervi at gmail.com
Wed Apr 2 09:05:56 EDT 2008


I have tried the following code:

#!/usr/local/bin/python
import _mysql
import MySQLdb
host = 'mysqldb2.ehost-services.com'
user = 'user'
passwd = 'pass'
db = 'bre'
print 'Content-Type: image/jpeg\r\n'
print '<html><body>\nHi!\n'
db=MySQLdb.connect(host=host, user=user, passwd=passwd, db=db)
c=db.cursor()
imgfile=open("1.jpg",'rb')
f = imgfile.read()
sqlstr="insert into photo (id, img) values ('1', '" +
_mysql.escape_string(imgfile.read()) +"');"
c.execute(sqlstr)
imgfile.close()
c.close()
print '\nBye!\n</body></html>'

which prints Hi! but not Bye! and gives me an HTTP 200 error. I threw the
line
f = imgfile.read()
in there just to make sure it is reading the imgfile. Also, I tested it with
all the import statements alone to make sure it was importing everything. So
the problem is the c.execute statement. Please advise.
TIA,
Victor
On Tue, Apr 1, 2008 at 1:37 PM, Gabriel Genellina <gagsl-py2 at yahoo.com.ar>
wrote:

> En Tue, 01 Apr 2008 09:36:00 -0300, Victor Subervi
> <victorsubervi at gmail.com> escribió:
>
> > Hi;
> > I´m trying to figure out how to upload images into a MySQL database.
> > (Yes,
> > that is what I want to do.) I have a form that asks for data, like this:
> > 1ra Foto Pequeña:
> > <input type='file' name='pic1' />
> > Then I send that form to a python script that processes like this:
> > cursor.execute('insert into products (' + col_names + ') values (' +
> > col_values + ');')
> > where col_names is all the names of the columns and col_values,
> > obviously,
> > the values. Works fine for strings and digits. Not so well for files :)
> > What
> > do?
>
> Always use bound parameters - not only it's easier and less error prone,
> it's safer too. How parameters are specified depends on the DBAPI module
> you're using - read the module documentation. I think MySQLdb accept
> dictionary-like marks:
>
> values = {'name': 'Red jar',
>           'descr': 'A nice red jar',
>           'pic': binary(picdata)
>          }
> cursor.execute('''insert into products (name,description,picture)
>     values (%(name)s, %(descr)s, %(pic)s);''', values)
>
> See PEP249 http://www.python.org/dev/peps/pep-0249/ and the documentation
> for your database module.
>
> --
> Gabriel Genellina
>
> --
> http://mail.python.org/mailman/listinfo/python-list
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080402/504b4e60/attachment.html>


More information about the Python-list mailing list