1

Error message 'Execution failed on sql ... expecting string, unicode or buffer object' is returned when trying to pass a Python string variable to a SQL query using cx_Oracle. Any help on this issue is greatly appreciated, thanks!

import pandas as pd
import cx_Oracle as ora

var = 'string'

conn = ora.connect('connection_string')
df = pd.read_sql(("SELECT * FROM table WHERE field LIKE '%s'", (var)), conn)
df.head()
0

2 Answers 2

3

To avoid the chance of SQL-injection attack you should pass the variable in the params keyword argument:

df = pdsql.read_sql("""SELECT * 
                       FROM table 
                       WHERE field LIKE %(var)s""", conn, params={'var':'string%',})
Sign up to request clarification or add additional context in comments.

Comments

1
pd.read_sql("SELECT * FROM table WHERE field LIKE '{}'".format(var), conn)

This should do it. You were trying to pass a tuple to a function instead of string/unicode object.

1 Comment

Don't do this with untrusted input. That is how SQL injection happens. Instead use parameter substitution: stackoverflow.com/a/24418294/3901060

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.