0

I am trying to use value of variable to be used inside MySQL query.

So, I have a first query (Sql1) to get the count (variable name = rowcount).

sql1 = ' select count(*) from ' \
       '( ' \
       ' select course_id, record_id .. ' \
       ' group by record_id '\
       ' ) src '
cursor.execute(sql1)
rowcount = cursor.fetchall()

I am trying to use the value of variable rowcount (for example 7) to be used in next MySQL query (Sql2).

For example, next query (Sql2) that I am thinking is something along this line.

sql2 = ' select course_id from '\
       ' ( select * from Courses order by course_id desc limit %s' \
       ' ) sub order by course_id asc '   

rowcount1 = ?
cursor.execute(sql2, rowcount1)

How can I pass the value of rowcount into next query where it states "rowcount1 = ? "

Java
  • 1,208
  • 3
  • 15
  • 29
  • Don't forget Python has [`"""` for multi-line strings](https://stackoverflow.com/questions/10660435/pythonic-way-to-create-a-long-multi-line-string). What you've got here is a real mess by comparison. – tadman Aug 30 '17 at 17:25
  • @coldspeed Thanks for previous comment. I am trying to carry the value of 1st query to be used for 2nd query. I modified the original code. – Java Aug 30 '17 at 17:27
  • If you fetched the count in the first, just pass it into the second. I don't know why you're using two different variable names here. – tadman Aug 30 '17 at 17:28
  • I tried using the variable rowcount on second query directly, but I am getting error. – Java Aug 30 '17 at 17:31
  • The #1 thing to remember here is if you get an "error" then it's very important to include that error in your question. – tadman Aug 30 '17 at 17:33
  • Thanks tadman. The error was due to the value of rowcount being Tuple inside Tuple. After I converted into Integer, it worked. – Java Aug 30 '17 at 17:40

1 Answers1

2

I have found a similar question here that is also looking for using variables in sql statement and has 4 answers to it.

May be you can get your answer from there:)

Amrit Singh
  • 143
  • 1
  • 7