MySQLdb

K

Kill Joy

Hi all.

I have a mod_python script with two query:

cursor = db.cursor()

sql = 'SELECT * FROM users where username=\'' + username +'\''
cursor.execute(sql)
result = cursor.fetchall()
num = int(cursor.rowcount)

if num == 0 :
sql2 = 'insert into users values (null, \'' + username + '\', \'' +
password +'\', \'no\',\'fdfdf\')'
cursor.execute(sql2)
warning = "Registration ok"
else :
warning = "EXIST!"

The first query is executed... but not the second. It doesn't insert.
Why?
I'm a newbie... sorry.

Many thanks.


K
 
G

Gerald Walker

Kill said:
Hi all.

I have a mod_python script with two query:

cursor = db.cursor()

sql = 'SELECT * FROM users where username=\'' + username +'\''
cursor.execute(sql)
result = cursor.fetchall()
num = int(cursor.rowcount)

if num == 0 :
sql2 = 'insert into users values (null, \'' + username + '\', \'' +
password +'\', \'no\',\'fdfdf\')'
cursor.execute(sql2) db.commit()
warning = "Registration ok"

else :
warning = "EXIST!"

The first query is executed... but not the second. It doesn't insert.
Why?
I'm a newbie... sorry.

Many thanks.

I added db.commit() after cursor.execute(sql2).
 
D

Dennis Lee Bieber

Hi all.

I have a mod_python script with two query:

cursor = db.cursor()

sql = 'SELECT * FROM users where username=\'' + username +'\''
cursor.execute(sql)

And in future... DON'T do that! Any data items should be passed to
the DB-API for proper handling...

sql = "select * from users where username = %s"
cursor.execute(sql, (username,)) #pass as a tuple, hence (,)
result = cursor.fetchall()
num = int(cursor.rowcount)

if num == 0 :
sql2 = 'insert into users values (null, \'' + username + '\', \'' +
password +'\', \'no\',\'fdfdf\')'
cursor.execute(sql2)

Same comment (heck, I'm going to have to bring up Python just to
decode that mess of mixed escaped quote marks... If you triple quote the
string, you don't have to use escapes internally! (You can even
multi-line the query)

sql2 = """insert into users
values (null, %s, %s, 'no', 'fdfd')"""
cursor.execute(sql2, (username, password))


ANY data value that could come from a user's input should be passed
using placeholders in the SQL, and a tuple of parameters in the
execute() call. That way the DB-API ensures the parameter is safe. After
all, presuming your new user types in the password (shown as an
assignment here)
"insert into users values (null, 'Who me', 'yes, why not', 'no',
fdfdf');drop table users;#', 'no','fdfdf')"
.... look at the resulting SQL... Perfectly valid insert statment --
followed by a table drop!
 

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,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top