Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set user-defined variable in Python MySQLdb?

So My problem is this, I have a query that uses Mysql User-defined variable like: @x:=0 SELECT @X:=@X+1 from some_table and this code returns a column from 1-1000.

However, this query doesn't work if I sent it through mySQLdb in Python.

connection =MySQLdb.Connect(host='xxx',user='xxx',passwd='xxx',db = 'xxx')
cursor = connection.cursor
cursor.execute("""SET @X:=0;SELECT @X:=@X+1 FROM some_table""")
rows = cursor.fetchall()
print rows

It prints a empty tuple.

How can I solve this?

Thanks

like image 611
zsljulius Avatar asked Jul 24 '11 13:07

zsljulius


2 Answers

Try to execute one query at a time:

cursor.execute("SET @X:=0;");
cursor.execute("SELECT @X:=@X+1 FROM some_table");
like image 92
spacediver Avatar answered Oct 24 '22 19:10

spacediver


Try it as two queries.

If you want it to be one query, the examples in the comments to the MySQL User Variables documentation look like this:

SELECT @rownum:=@rownum+1 rownum, t.* FROM (SELECT @rownum:=1) r, mytable t;

or

SELECT if(@a, @a:=@a+1, @a:=1) as rownum

See http://dev.mysql.com/doc/refman/5.1/en/user-variables.html

like image 34
agf Avatar answered Oct 24 '22 19:10

agf