0

I have the following code:

I have a query which gives me result from MySQL:

import MySQLdb
db_mysql=MySQLdb.Connect(user=...,passwd=...,db=..., host=...)
cur = db_mysql.cursor(MySQLdb.cursors.DictCursor)
cur.execute ("""SELECT X,Y,Z FROM tab_a""")
for row in crs.fetchall () :
     do things...

X is defined in MySql as: bigint(20) unsigned .

In python it shows the number with l suffix : 1445l

according to this Why do integers in database row tuple have an 'L' suffix? it's a normal behavior for python 2.7

The thing is that I need to use X value in other queries so I saved it: save_x = str(row["X"]) This auto remove the l suffix.

Now, if I do:

cur.execute ("""SELECT A FROM tablx where id='%s'""")%save_x

Doesn't work. it says:

TypeError: unsupported operand type(s) for %: 'long' and 'str'

How can I make it work? I know that it doesn't work beacsue i'm comparing long with string, but if I leave it as a number it stays with L suffix and this also doesn't work.

What can I do to fix it?

Community
  • 1
  • 1
java
  • 1,124
  • 2
  • 14
  • 33

2 Answers2

2

I'm not so familiar with the old syntax, but try:

cur.execute ("SELECT A FROM tablx where id='{save_x}'".format(save_x=save_x))

and report whether it helped.

mstuebner
  • 406
  • 2
  • 15
2

The main problem might be coming from the fact that your are not formatting the query argument but your are trying to format the function/method call itself.

Try to change this instruction :

cur.execute ("""SELECT A FROM tablx where id='%s'""")%save_x

into :

cur.execute("""SELECT A FROM tablx WHERE id='%s'"""%save_x)

By the way, you should take care about the output string. If save_x == 1, with the '%s' you will get something like:

"SELECT A FROM tblx WHERE id='1'"

This might return you an error from the db if the awaited type is a long or an int.

Alex C.
  • 166
  • 3
  • 9