【问题标题】:import a pd.read_sql() DataFrame from another File to process it further从另一个文件导入一个 pd.read_sql() DataFrame 以进一步处理它
【发布时间】:2021-08-20 18:50:07
【问题描述】:

我想从 read_datasets.py 文件中导入一个数据帧并在 main.py 中处理它。另外使用 mysql 连接的函数。

main.py:

    import mysql.connector
    import pandas as pd



def con():
    connection = None
    
    try:
        # declaration of default mysql settings
        connection = mysql.connector.connect(
        host="xx",
        user="xx",
        passwd="xx",
        db="xx",
        )
    # If connection is not successful    
    except:
        print("cant connect to database")
        return 0
    
    # if connection is successfull
    print("connected")
    # Making Cursor Object For Query Execution
    cursor = connection.cursor()

if __name__ == '__main__':

  print("actually in main.py")


  #talk to connection mysql
  temp1 = pd.read_sql("SELECT xx FROM xx", con() )
  # filter all NAN Vlaues in the Dataframe
   temp1 = temp1.dropna()

在 read_datasets.py 中:

import pandas as pd
from main import con

temp1 = pd.read_sql("SELECT xx FROM xx", con)
# filter all NAN Vlaues in the Dataframe
temp1 = temp1.dropna()

我得到了错误:

AttributeError: 'NoneType' 对象没有属性 'cursor'

【问题讨论】:

  • cursor = connection.cursor() 这是什么?
  • 一个允许我在 python 中命令数据库的游标,对吧?
  • 不应该是read_datasets.py中的temp1 = pd.read_sql("SELECT xx FROM xx", con())吗? (好像忘了打con,应该是con()而不是con

标签: python mysql pandas dataframe


【解决方案1】:

我只对使用 SQLAlchemy 执行此操作有经验,因此我将发布如何使用该包执行此操作:

from sqlalchemy import create_engine

def db_connection(self):
    engine = create_engine('mysql+pymysql://{0}:{1}@{2}:3306/{3}'.format(username, password, host, db_name), echo=False)
    connection = engine.connect()
    return connection

^我没有定义密码等变量,但请注意上面的代码将不起作用,因为你需要这样做!

然后您可以调用:

pd.read_sql("SQL query here", db_connection())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 2014-09-14
    • 2021-03-21
    • 2021-02-10
    相关资源
    最近更新 更多