无法创建第二个数据帧python pandas

时间:2016-10-18 21:19:54

标签: 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)

1 个答案:

答案 0 :(得分:3)

为什么不使用pd.read_sql_query(“your_query”,conn)这会将查询结果作为数据帧返回,并且需要的代码更少。你也把光标设置在顶部的cursor.execute(strsql),然后你试图在你的for循环中再次调用执行游标,但你不能再调用游标上的执行你必须设置cursor = conn.cursor()再次。