1

Just started learning Pandas and tumbled over "read_sql_query":

In my code there are multiple create statements and executing them with "read_sql_query" is making the job redundant like:

import pandas as pd
import sqlite3 

con = sqlite3.connect("/Users/sqlite_example.db3")

query_1 = ("Create table temp_1")
pd.read_sql_query(query_1,con)

query_2 = ("Create table temp_1")
pd.read_sql_query(query_2,con)

query_3 = ("Create table temp_3")
pd.read_sql_query(query_3,con)

My questions are:

  1. Can't all the queries be passed in single "pd.read_sql_query"
  2. Can opening a connection with DB be avoided everytime i.e. con parameters once
    is not sufficient enough rather than to pass it everytime?

I tried looking into the documentations and web portals but couldn't came across anything like this. In the "read_sql_query" everytime the "query,con" has to be passed otherwise failing to do so is giving error.

Please help to understand the concept and way to pass multiple queries and establishing connection only one time rather than multiple times.

I hope this will help others also who might face similar sort of issue innear future.

1
  • read_sql is for reading the result out from sql statement, for create query why do you want to read that in a dataframe? Commented Jun 27, 2018 at 6:40

1 Answer 1

3

This should do the trick.

Note: executelist() is used to execute multiple sql statements in the same query.

con = sqlite3.connect("/Users/sqlite_example.db3")
cursor=con.cursor()

query_1 = "Create table temp_1;
           Create table temp_2;
           Create table temp_3;"

cursor.executelist(query)
Sign up to request clarification or add additional context in comments.

Comments

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.