I am trying to do a simple
- INSERT into a localhost MySQL 5.7 db
- with a Python 2.7 script
Nothing fancy but that is exactly the result I get - nothing.
I tested the darn thing bit by bit in a separate test script, no errors raised but no data inserted into table, as well. Problem occurs at the first SQL variable (probably) and there is one error in the last try/catch.
I guess I am not doing the data type conversion correctly?
Here is the code:
#!/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()
Following sql and for could be written badly:
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]
Here is the error, goes to "except":
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()
And if I remove try block:
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 ❯
For what it's worth, this is the sample of a list that gets read from Excel in the beginning of the script (maybe 'None' is making problems?):
[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]
TypeError: %d format: a number is required, not strbut I don't know how to solve this? Is it the db that's returning a different format or ...? Also, when I check in my other Shell instance I see that no rows were added to this particular table.