I'm using MySQLdb to upload a lot of data from text files into a MySQL server. This works fine if I manually prepare a string such as 'as', '123', 12, 23, but I can't figure out how to loop through a list to generate this as I need to concatenate strings and ints.
An example of an insert statement that works is as follows:
""" INSERT INTO ACS(ST, CODE, BC001, BC002, BC003)
VALUES ('AK', '1234567', 20, 30, 40)"""
This is how I have tried to generate this statement from a list:
import MySQLdb
# sample data
table = 'TestTable'
header = ['ST', 'CODE', 'BC001', 'BC002', 'BC003']
values = [['AA', '1234567', 20, 30, 40], ['BB', '1234567', 20, 30, 40], ['CC', '1234567', 20, 30, 40],['DD', '1234567', 20, 30, 40]]
# local SQL server on my computer
db = MySQLdb.connect (host = 'localhost', user = 'root', passwd = '', db = 'test')
# prepare a cursor object using cursor() method
cursor = db.cursor()
# header columns
sql1 = '('
for i in range(len(header)):
sql1 += header[i] + ','
sql1 = 'INSERT INTO ' + table + sql1[:-1] + ')'
# now loop through data values and combine with header each time
for i in range(len(values)):
sql2 = ''
for j in range(len(values[i])):
sql2 += values[i][j] + ',' #error occurs here
# structure: sql2 = """ VALUES ('AA', '1234567', 20, 30, 40)"""
sql2 = 'VALUES ' + table + sql2[:-1] + ')'
sql = sql1 + sql2
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
The error message I get is
TypeError: unsupported operand type(s) for +: 'int' and 'str'
and I understand why that is occurring, but I can't figure out an alternative way of generating the string. Is there a better way of producing these strings?
I'm using Python27 on Win7 64 bit.