2012-10-10 165 views
1

對於當前任務,我必須使用python將2個.txt文件導入到MySQLdb中。我遇到了很大的麻煩。我嘗試了各種方法,而我根本做不到。將文本文件導入到mysqldb中

我通過這個網站和其他許多人在過去幾天搜索,我根本無法得到這個工作。每當我嘗試將其他人的解決方案適用於自己的代碼時,它都會失敗 - 所以我想我應該直接尋求我自己的代碼的幫助。

這是我到目前爲止有:

import MySQLdb 

# connect to database 
mydb = MySQLdb.connect("localhost","root","0dy5seuS","cars_db") 

# define the function 
def data_entry(cars_for_sale): 

# cursor creation 
    cursor = mydb.cursor() 

#load the file 'cars_for_sale.txt' into the database under the table 'cars_for_sale' 

    sql = """LOAD DATA LOCAL INFILE 'cars_for_sale.TXT' 
     INTO TABLE cars_for_sale 
     FIELDS TERMINATED BY '\t' 
     LINES TERMINATED BY '\r\n'""" 

    #execute the sql function above 
    cursor.execute(sql) 

    #commit to the database 
    mydb.commit() 

    #call data_entry(cars_for_sale) function 
    data_entry(cars_for_sale) 

    mydb.close() 

我幾乎不能換我的頭周圍,任何幫助,將不勝感激它。 我現在得到的測試功能如下反饋:

Trying: data_entry("cars_for_sale") Expecting: The number of rows inserted to cars_for_sale is 7049 **************************************** File "main", line 4, in main Failed example: data_entry("cars_for_sale") Exception raised:

Traceback (most recent call last):

File "C:\Python27\lib\doctest.py", line 1289, in __run compileflags, 1) in test.globs

File "", line 1, in data_entry("cars_for_sale")

File "E:/Uni/104/Portfolio 2/MediumTask_DataStatistics/question/TEST2_data_statistics.py", line 270, in data_entry data_entry(cars_for_sale) *it repeats this last portion several hundred/thousand times"

The following few lines are after the repeated error above.

File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 243, in cursor return (cursorclass or self.cursorclass)(self)
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 51, in init from weakref import proxy RuntimeError: maximum recursion depth exceeded while calling a Python object

我知道,這是一個無限循環,雖然我不知道如何阻止它。 感謝

+1

歡迎來到SO。不幸的是,這不是一個真正的教程網站。請閱讀[常問問題]和[提問]以獲得編寫適當問題的提示。 –

+0

你在哪裏調用你創建的函數?你已經創建了兩個具有相同名稱但不同參數類型的函數?那個有什麼用? – Shubhansh

+0

關於具有相同名稱的2個函數:data_entry(「cars_for_sale」)data_entry(「car_details」)這是因爲此評估的測試功能測試這些函數名稱。我想不出任何其他方式。 – PeteB987

回答

1

下面的代碼重新您的錯誤"RuntimeError: maximum recursion depth exceeded while calling a Python object"

def data_entry(cars_for_sale): 
    data_entry(cars_for_sale) 

你不需要在這裏遞歸(這是無論如何使用不當)。

I'm aware that this is an infinite recursion although I have no idea how to stop it.

只需卸下data_entry函數內data_entry電話。