2017-08-28 28 views
0

我在ubuntu中使用了相同的代碼,它工作正常,但是當我試圖在windows中運行它時,它給了我一個「()」輸出。可能是什麼原因。我是這個新的領域,我需要assistance.`python中沒有插入數據的數據

import csv 
import string 
import MySQLdb 

with open('cool1.txt','r') as csvfile: 
    scoreFileReader=csv.reader(csvfile) 
    scoreList=[] 
    for row in scoreFileReader: 
     if len(row) !=0: 
      scoreList=scoreList + [row] 



csvfile.close() 

print(scoreList) 

temp=str(scoreList).translate(string.maketrans('', ''), '[]\'') 
#print(temp) 
db = MySQLdb.connect("localhost","root","","test123") 
    #setup cursor 
cursor = db.cursor() 
#create anooog1 table 
cursor.execute("DROP TABLE IF EXISTS db1234") 

sql = """CREATE TABLE db1234 (
      uid VARCHAR(100) NOT NULL, 
      price INT(100) NOT NULL)""" 
cursor.execute(sql) 

try: 
    cursor.execute("""INSERT INTO db1234 VALUES (%s,%s)""",(scoreList)) 
    db.commit() 
except:  
    db.rollback() 
#how table 
cursor.execute("""SELECT * FROM db1234;""") 
print cursor.fetchall() 
db.close() 

和文本文件中的數據看起來好像是這些:

E0 C1 7F 7A 

0 

除了錯誤移除後,來到像這樣的

[['E0 C1 7F 7A'], ['0']] 
Traceback (most recent call last): 
    File "csvfile_writer2.py", line 31, in <module> 
    cursor.execute("""INSERT INTO db1234 VALUES (%s,%s)""",(scoreList)) 
    File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 174, in execute 
    self.errorhandler(self, exc, value) 
    File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler 
    raise errorclass, errorvalue 
_mysql_exceptions.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'),("\'0\'",))\' at line 1') 

除外條款有人來

C:\Users\supar\Desktop>python csvfile_writer2.py 
[['E0 C1 7F 7A'], ['0']] 
() 

C:\Users\supar\Desktop> 
+0

不要使用空'除外:'條款。您可能會收到阻止數據插入的錯誤。 – bernie

+0

輸出是這樣的 – Fiore

+0

您有兩個佔位符和一個項目插入每次迭代。這是行不通的。 – bernie

回答

1

之前,您有兩個佔位符,只有一個項目可以插入在每次迭代。所以只需將佔位符的數量減少到一個。

而且因爲你有集裝箱的容器要插入使用.executemany(),例如:

cursor.executemany("""INSERT INTO db1234 VALUES (%s)""", scoreList)