pythonsqlmysql

Conversion issues in sql - GREATEST(CEILING())


Below one working fine with the float values.

import mysql.connector
conn = mysql.connector.connect()
cur = conn.cursor()

cur.execute('SELECT GREATEST(CEILING(Tot_Weight + 3.4),4.5) FROM TestTable order by id asc;')
print(cur.fetchall())

If I pass parameters to the query then facing conversion issues. Tried with str(Wt1) and str(Wt2) but no luck.

Wt1 = 7.02
Wt2 = 5.4
cur.execute('SELECT GREATEST(CEILING(Tot_Weight +'+ Wt1 +')', Wt2 +') FROM TestTable order by id asc;')
print(cur.fetchall())

TypeError: can only concatenate str (not "float") to str

Please somebody help on this.


Solution

  • This should work:

    cur.execute('SELECT GREATEST(CEILING(Tot_Weight +' + str(Wt1) + '), ' + str(Wt2) +') FROM TestTable order by id asc;')
    

    But a better way to do this is to use parameterized queries:

    cur.execute('SELECT GREATEST(CEILING(Tot_Weight + ?), ?) FROM TestTable order by id asc;', (Wt1, Wt2))