Python:熊猫read_sql_query

时间:2018-06-27 05:20:35

标签: python sql pandas

刚开始学习熊猫,然后翻阅“ read_sql_query”:

在我的代码中,有多个create语句,使用“ read_sql_query”执行它们会使工作变得多余,如:

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)

我的问题是:

  1. 不能将所有查询都传递给单个“ pd.read_sql_query”
  2. 每次都可以避免打开与数据库的连接,即一次使用con参数
    不足以代替每次都通过?

我尝试研究文档和Web门户,但找不到类似的东西。每次都必须在“ read_sql_query”中传递“ query,con”,否则将出错。

请帮助您理解一次传递而不是多次传递多个查询和建立连接的概念和方式。

我希望这会帮助其他在不久的将来可能会面临类似问题的人。

1 个答案:

答案 0 :(得分:2)

这应该可以解决问题。

注意:executelist()用于在同一查询中执行多个sql语句。

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)
相关问题