无法创建第二个DataFrame蟒蛇 pandas

2022-04-25 00:00:00 python pandas pyodbc

问题描述

我创建第二个数据框时,它没有加载值。对于它为什么不起作用,有什么帮助吗?当我让我的光标成为一个列表时,它里面有一堆值,但无论出于什么原因,当我第二次尝试用 pandas 加载正常的数据框时,它不起作用。

我的代码:

    conn = pyodbc.connect(constr, autocommit=True)
    cursor = conn.cursor()
    secondCheckList = []
    checkCount = 0
    maxValue = 0
    strsql = "SELECT * FROM CRMCSVFILE"
    cursor = cursor.execute(strsql)
    cols = []
    SQLupdateNewIdField = "UPDATE CRMCSVFILE SET NEW_ID = ? WHERE Email_Address_Txt = ? OR TELEPHONE_NUM = ? OR DRIVER_LICENSE_NUM = ?"
    for row in cursor.description:
        cols.append(row[0])
    df = pd.DataFrame.from_records(cursor)
    df.columns = cols
    newIdInt = 1
    for row in range(len(df['Email_Address_Txt'])):
        #run initial search to figure out the max number of records. Look for email, phone, and drivers license, names have a chance not to be unique
        SQLrecordCheck = "SELECT * FROM CRMCSVFILE WHERE Email_Address_Txt = '" + str(df['Email_Address_Txt'][row]) + "' OR TELEPHONE_NUM = '" + str(df['Telephone_Num'][row]) + "' OR DRIVER_LICENSE_NUM = '" + str(df['Driver_License_Num'][row]) + "'"
##        print(SQLrecordCheck)
        cursor = cursor.execute(SQLrecordCheck)
## maxValue is indeed a list filled with records
            maxValue =(list(cursor))
## THIS IS WHERE PROBLEM OCCURS
        tempdf = pd.DataFrame.from_records(cursor)

解决方案

为什么不直接使用pd.Read_SQL_Query("Your_Query",conn)这将以数据帧形式返回查询结果,并且需要的代码更少。此外,您在顶部将Cursor设置为cursor.Execute(Strsql),然后在for循环中再次尝试对Cursor调用Execute,但不能再对Cursor调用Execute,您必须再次设置Cursor=Connec.Cursor()。

相关文章