2

I have data in SQL and I want to read some data out from it with variable instead of using number like "953381". Having no idea why I just can't use var = 9553381, directly.

df = pd.read_sql('select name, data, from sheet where name = "953381" ', conn,
                index_col=['date'], parse_dates=['date'])
4
  • 1
    What is the error/output you are getting using this code? Commented Jun 13, 2018 at 12:47
  • DatabaseError: Execution failed on sql, no such column: var Commented Jun 13, 2018 at 13:10
  • Is the extra comma after "data" causing the error? Commented Jun 13, 2018 at 13:17
  • Should be not, since I can get correct data if I using numbers, 953381. Commented Jun 13, 2018 at 13:19

4 Answers 4

0

SQL doesn't understand double quotes. Use single quotes:

x = "953381"
query = "SELECT name, data FROM sheet WHERE name = '%s'" % x # x inside single quotes
df = pd.read_sql(query, conn, index_col=['date'], parse_dates=['date'])
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the help!!! It works !!!!
Do not use string formatting to put SQL values into a query! This is never a good idea, it opens up the code for SQL injection attacks, and robs the database of an opportunity to reuse optimised queries. Use ? or %s placeholders (depends on the database driver) and pass in the value to read_sql() via params=(x,).
0

I guess that is what you are looking for:

var =  "953381" 
df = pd.read_sql('select name, data, from sheet where name =' + var, conn,
                index_col=['date'], parse_dates=['date'])

Comments

-1

Is this what you are looking for ?

var = "953381"
df = pd.read_sql('select name, data, from sheet where name =' + var , conn,
            index_col=['date'], parse_dates=['date'])

2 Comments

Thank you for the suggestion. but it still can't find the data.
Do not use string formatting to put SQL values into a query! This is never a good idea, it opens up the code for SQL injection attacks, and robs the database of an opportunity to reuse optimised queries. Use ? or %s placeholders (depends on the database driver) and pass in the value to read_sql() via params=(x,).
-1

Is this a case for .format()?

x = "953381"
sql_str = 'select name, data, from sheet where name = "{}"'.format(x)

2 Comments

I tried, not this case, but thank you the suggestion!
Do not use string formatting to put SQL values into a query! This is never a good idea, it opens up the code for SQL injection attacks, and robs the database of an opportunity to reuse optimised queries. Use ? or %s placeholders (depends on the database driver) and pass in the value to read_sql() via params=(x,).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.