2016-02-26 105 views
0

我試圖做一個簡單的Python和MySQLdb的 - 數據未插入數據轉換錯誤太

  • 插入到本地主機的MySQL5.7分貝
  • 有一個Python 2.7腳本

沒有幻想,但這正是我得到的結果 - 沒有。

我在一個單獨的測試腳本中測試了一點一滴的事情,沒有錯誤引發,但沒有數據插入到表中。問題發生在第一個SQL變量(可能)上,最後一個try/catch中有一個錯誤。

我想我沒有正確地做數據類型轉換

下面是代碼:

#!/usr/bin/python 

import MySQLdb 
import pandas as pd 
import numpy as np 
import xlwings as xw 

# ---------- Connect to Excel sheet, get data (list of lists) 
wb = xw.Workbook('/users/edchigliak/sites/xlwings/baza.xlsx') 
data = xw.Range('dimensions', 'A2:F71').value 

# ---------- Open database connection, insert data into table 
db = MySQLdb.connect("localhost","root","/pass/","budgeteer") 
cursor = db.cursor() 

SQL可寫的不好:

sql = """INSERT INTO dimensions(dimension, dimType, abbreviation, translationHr, code) VALUES (%s, %d, %s, %s, %d)""" 

for row in data: 
    try: 
     cursor.execute(sql, row) 
     db.commit() 
    except: 
     db.rollback() 


# ---------- Check if INSERT successful 
sql = """SELECT * FROM dimensions""" 

try: 
    cursor.execute(sql) 

    # ---------- Fetch all the rows in a list of lists 
    results = cursor.fetchall() 

for row in cursor: 

    id = row[0] 
    dimension = row[1] 
    dimType = row[2] 
    abbreviation = row[3] 
    translationHr = row[4] 
    code = row[5] 

以下是錯誤,變爲 「除了」:

Error: unable to fetch data.

# Now print fetched result 
    print "Dim. ID: %d, Dim.: %s, Dim. type: %d, Abbrev.: %d, Translat.: %s, Code: %d" % (id, dimension, dimType, abbreviation, translationHr, code) 

except: 
    print "Error: unable to fetch data" 

db.close() 

如果我刪除try塊:(?也許「無」是決策問題)

python git:master ❯ python proba.py
Traceback (most recent call last):
File "proba.py", line 47, in
print "Dim. ID: %d, Dim.: %s, Dim. type: %d, Abbrev.: %d, Translat.: %s, Code: %d" % (id, dimension, dimType, abbreviation, translationHr, code) TypeError: %d format: a number is required, not str
python git:master ❯

對於它的價值,這是被從Excel中的腳本開始閱讀列表的樣本:

[1.0, u'austria', 1.0, u'at', None, 4.0]
[2.0, u'belgium', 1.0, u'be', None, 7.0]
[3.0, u'czech', 1.0, u'cz', None, 9.0]

+0

**請**不要使用裸露的除外。你很小心**隱藏**問題是什麼。不要這樣做。刪除該嘗試/完全除外,以便您可以看到實際提出的錯誤;那麼你應該能夠自己解決你的問題。 –

+0

謝謝Daniel Roseman :)。我在我的帖子的最後一個塊中做了這些,並且解釋器返回的錯誤是:'TypeError:%d格式:需要一個數字,而不是str',但我不知道如何解決這個問題?是數據庫返回一個不同的格式或...?另外,當我檢查我的其他Shell實例時,我發現沒有行被添加到這個特定的表中。 –

+1

不,我的意思是在cursor.execute循環中。但是你不應該在任何地方*做。 –

回答

1

你應該總是使用%s作爲參數標記(不%d等),無論值的類型:

sql = ("INSERT INTO dimensions(dimension, dimType, abbreviation, " 
     "translationHr, code) VALUES (%s, %s, %s, %s, %s)") 
cursor.execute(sql, row) 

數據庫驅動程序將爲您處理任何引用。

+0

如果我這樣做,並刪除第一個「try ... except」我得到這個錯誤:TypeError:不是所有在字符串格式轉換過程中轉換的參數:? –

+0

@AlexStarbuck:這意味着'row'有比佔位符數量更多的項目(5)。 –

+0

啊,當然!從Excel中我也得到'id'列,這在我的sql中不需要。所以我應該重寫'for row ...'語句,它將data []中每行的第一項排除在外。我做了這個,現在又出現了另一個錯誤:'_mysql_exceptions。OperationalError:(1366,「不正確的字符串值:'\\ xC4 \\ x87enja'列'translationHr'在第1行)」我猜它不知道如何將'None'轉換爲NULL –