如何通过MySQLdb Python将值插入表中

时间:2019-01-22 03:14:49

标签: python mysql mysql-python mysql-connector

所以在这里我试图将csv文件'employee_reviews.csv'的值存储到我的雇员表中。我正在读取文件,将其存储为字符串,然后将元素一路拆分为2D列表,然后将其循环遍历每一行。我敢肯定,这样做有更简单的方法。运行代码时,出现错误->

  

cur.execute(“ INSERT INTO(id,company,location,date,job_title,   摘要,优点,缺点,advice_to_management,总体评分,   work_balance_stars,culture_value_stars,career_opportunities_stars,   comp_benefit_stars,senior_management_stars,有用计数,链接)   价值   (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,% s)“,(int(row [0]),   行[1],行[2],行[3],行[4],行[5],行[6],行[7],行[8],   int(row [9]),第[10]行,第[11]行,第[12]行,第[13]行,第[14]行,   int(row [15]),row [16]))ValueError:int()的无效文字   以10为基数:“无”


import csv
import MySQLdb

mydb = MySQL.connect(host="host",user="user",passwd="passwd",db="Employee_Review")
cur = mydb.cursor()
#cur.execute("CREATE TABLE employees(id INT, company VARCHAR(20), location VARCHAR(40), dates DATE, job_title VARCHAR(20), summary VARCHAR(50), pros VARCHAR(1000), cons VARCHAR(1000), advice_to_management VARCHAR(50), overall_ratings INT, work_balance_stars VARCHAR(10), culture_value_stars VARCHAR(10), career_opportunities_stars VARCHAR(10), comp_benefit_stars VARCHAR(10), senior_management_stars VARCHAR(10), helpful_count INT, link VARCHAR(75) )")

f = open("employee_reviews.csv","r")
fString = f.read()

fList = []
for line in fString.split('\n'):
   fList.append(line.split(','))

for row in fList:
   if row == fList[0]:
      continue #skip the first row for it contains the name of the columns

   cur.execute("INSERT INTO (id, company, location, dates, job_title, summary, pros, cons, advice_to_management, overall_ratings, work_balance_stars, culture_value_stars, career_opportunities_stars, comp_benefit_stars, senior_management_stars, helpful_count, link) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",(int(row[0]), row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], int(row[9]), row[10], row[11], row[12], row[13], row[14], int(row[15]), row[16] ))
   mydb.commit()

mydb.close()

csv文件可以在这里找到: https://inclass.kaggle.com/petersunga/google-amazon-facebook-employee-reviews/discussion

1 个答案:

答案 0 :(得分:0)

CSV中的一个值是“ none”,无法在其中一个整数列中将其转换为整数。