简体   繁体   中英

Perform a query on a sql database with Python

I'm working on a python assignment and I am facing an issue. My question is the following:

"Write a query to select all rows from the sales table. Merge with the table returns by INNER JOIN on the Order ID . Put the result in a variable QUERY ."


So I wrote this code:

sales_row = pd.read_sql("SELECT * FROM sales", mydb)
QUERY = pd.merge(sales_row, returns, on = "Order ID", how = "inner")

It works, but then I'm asked to perform a query on the database so I wrote the following:

pd.read_sql_query(QUERY, mydb)

And I get the following error:

ObjectNotExecutableError: Not an executable object

What can I do to fix this issue?

I think the question is asking you to write a query which selects all rows and merges it. so your query would be something like

query = "Select * from sales inner join returns on order id"

If you see the read_sql_query documentation, you'll see the first argument must be a string, not a dataframe.

so after running the previous line I wrote, you can write

pd.read_sql_query(query, mydb)

where "query" is the string containing the SQL query

There seems to be a misunderstanding. pd.read_sql and pd.read_sql_query are (roughly) the same thing. From the doc of read_sql : This function is a convenience wrapper around read_sql_table and read_sql_query (for backward compatibility) .

The output of pd.read_sq is a Pandas DataFrame. You don't explicit what returns is, but I guess it also is a DataFrame. So you could simply do

sales_row = pd.read_sql("SELECT * FROM sales", mydb)
QUERY = sales_row.join(returns, on="Order ID", how="inner")

Note the use of join instead of merge .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM