passing artibrary strings into a database

S

schwehr

Hi All,

I was wondering if there is a helper library out there that will nicely
encode artibrary text so that I can put in into a TEXT field in a
database and then retrieve it without getting into trouble with ',",new
lines or other such things that would foul the sql insert call and or
be a security hazard? This feels like a newbee type question, but I
haven't found anything with a quick search.

Thanks,
-kurt
 
F

Fredrik Lundh

I was wondering if there is a helper library out there that will nicely
encode artibrary text so that I can put in into a TEXT field in a
database and then retrieve it without getting into trouble with ',",new
lines or other such things that would foul the sql insert call and or
be a security hazard?

don't ever use string formatting to add values to an SQL statement.
the right way to pass variables to the database engine is to use para-
meters (aka bound variables):

cursor.execute(
"insert into table (col1, col2) values ?, ?",
value1, value2
)

the exact marker depends on the database; use the paramstyle attribute
to figure out what's the right parameter marker to use for your database.
see the DB-API 2 spec for more information:

http://www.python.org/peps/pep-0249.html

</F>
 
D

Diez B. Roggisch

Hi All,

I was wondering if there is a helper library out there that will nicely
encode artibrary text so that I can put in into a TEXT field in a
database and then retrieve it without getting into trouble with ',",new
lines or other such things that would foul the sql insert call and or
be a security hazard? This feels like a newbee type question, but I
haven't found anything with a quick search.

Use paramtetrized cursor.execute(..) That is instead of doing

c.execute("insert into foo values ('%s')" % mytext)

do

c.execute("insert into foo values (?)", mytext)

Attention, the actual style of a parameter is dependand on your
database, e.g. oracle uses a differnet one:

c.execute("insert into foo values :)mytext)", dict(mytext=mytext))


The actual style to use is given in the docs, or can be queried with

connection.paramstyle

I recommend reading the DB-API 2.0 specs.

Diez
 
S

schwehr

Thanks! Looks like I need to get a newer version of pysqlite into the
fink package tree since pysqlite 1.0.1 does not appear support that
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top