【问题标题】:Read External SQL File into Pandas Dataframe将外部 SQL 文件读入 Pandas 数据框
【发布时间】:2018-03-23 11:47:19
【问题描述】:

这是一个我无法找到答案的简单问题。我有一个带有两个命令的 .SQL 文件。我想让 Pandas 将这些命令的结果提取到 DataFrame 中。

SQL 文件的命令就是这样,较长的查询使用今天的日期。

SET @todaydate = DATE(NOW());
SELECT ...long query....;

在建立连接 (prod_db) 后,我尝试通过以下方式使用 read_sql,并收到错误消息“'NoneType' object is not iterable”

sqlpath = 'path.sql'
scriptFile = open(sqlpath,'r')
script = scriptFile.read()
df = pd.read_sql(script,prod_db) 

我也尝试使用此处描述的功能和方法reading external sql script in python,但我不确定如何将结果放入 pandas 数据框(或者我可能遗漏了一些东西)。它似乎没有读取结果,因为我反复得到“跳过命令”。

def executeScriptsFromFile(filename):
    fd = open(filename, 'r')
    sqlFile = fd.read()
    fd.close()
    # all SQL commands (split on ';')
    sqlCommands = sqlFile.split(';')
    # Execute every command from the input file
    for command in sqlCommands:
        try:
            c.execute(command)
        except OperationalError, msg:
            print "Command skipped: ", msg
df = executescriptsfromfile(sqlpath)

【问题讨论】:

    标签: python pandas dataframe path mysql-python


    【解决方案1】:

    我有一个可能适合您的解决方案。它应该给你一个不错的小pandas.DataFrame

    首先,您必须阅读 sql 文件中的查询。然后只需使用pd.read_sql_query() 而不是pd.read_sql()

    我相信你知道,但这里是函数的文档:http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.read_sql_query.html#pandas.read_sql_query

    # Read the sql file
    query = open('filename.sql', 'r')
    
    # connection == the connection to your database, in your case prob_db
    DF = pd.read_sql_query(query.read(),connection)
    query.close() 
    

    我可以向您保证,它可以与 T-SQL 一起使用,但我从未将它与 MySQL 一起使用。

    【讨论】:

    • 我可以确认这在 MySQL 中完美运行。非常感谢:)
    • 您能解释一下如何设置connection 吗?设置本地临时 SQL 连接的最简单方法是什么?
    • 可以使用connection = cx_Oracle.connect(dsn = "DBCON.LD") 连接到数据库,例如连接到 Oracle 数据库
    • 推荐使用上下文管理器为像我一样在这里闲逛的人打开/关闭文件! with open(sql_file,'r') as f:... 当您将文件读入 pandas 数据框时,它将处理文件的关闭。
    • 只是为了新用户的信息,连接将通过sqlalchemy import sqlalchemy as db # SQLAlchemy connectable connection = db.create_engine('sqlite:///filename.sql').connect()
    【解决方案2】:

    这是对我的工作方式的 MWE:

    query = open('./query_file.sql', 'r') 
    
    db_config = {
                'server': server address,
                'port': port,
                'user': user,
                'password': password,
                'database': db name
            }
    
        try:
            sql_conn = pymssql.connect(**db_config)
            logging.info('SQL connection is opened')       
            avise_me_df = pd.read_sql(query.read(),sql_conn)
            logging.info('pandas df recorded')
        except OperationalError as e:
            connected = False
    
            logging.error('Error reading data from SQL table')
        else:
            connected = True
        finally:
            if connected:
                sql_conn.close()
                logging.info('SQL connection is closed')
    

    我希望这可能会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-25
      • 2020-08-27
      • 1970-01-01
      • 2019-11-25
      • 1970-01-01
      • 2012-12-11
      • 2021-01-21
      相关资源
      最近更新 更多