我試圖做一個簡單的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]
**請**不要使用裸露的除外。你很小心**隱藏**問題是什麼。不要這樣做。刪除該嘗試/完全除外,以便您可以看到實際提出的錯誤;那麼你應該能夠自己解決你的問題。 –
謝謝Daniel Roseman :)。我在我的帖子的最後一個塊中做了這些,並且解釋器返回的錯誤是:'TypeError:%d格式:需要一個數字,而不是str',但我不知道如何解決這個問題?是數據庫返回一個不同的格式或...?另外,當我檢查我的其他Shell實例時,我發現沒有行被添加到這個特定的表中。 –
不,我的意思是在cursor.execute循環中。但是你不應該在任何地方*做。 –