import csv
import MySQLdb
print "DB connecting start"
mydb = MySQLdb.connect(user='root',passwd='root',host='localhost', db='ECDatabase' )
print "DB connecting end"
cursor = mydb.cursor()
csv_data = csv.reader(file('data/productClick.csv'))
for row in csv_data:
cursor.execute("INSERT INTO ProductClick ( userId, productId, clickCount ) VALUES ( '%s', '%s', '%s' );", row)
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"
出現錯誤:TypeError: not enough arguments for format string
原因是csv的內容為tab分隔
修改
import csv
import MySQLdb
print "DB connecting start"
mydb = MySQLdb.connect(user='root',passwd='root',host='localhost', db='ECDatabase' )
print "DB connecting end"
cursor = mydb.cursor()
csv_data = csv.reader(file('data/productClick.csv'))
for row in csv_data:
data=row[0].split('\t')
# query = """insert into newsletter_subscriber (id, name, email) values ('%s', '%s', '%s')""" %(data[0], data[1], data[2])
cursor.execute("INSERT INTO ProductClick ( userId, productId, clickCount ) VALUES ( '%s', '%s', '%s' );" %(data[0], data[1], data[2]))
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"
沒有留言:
張貼留言