CSV文件到MySQL数据库,插入不起作用

时间:2017-11-02 02:09:41

标签: python mysql csv insert

我正在尝试将CS​​V文件发送到MYSQL数据库,但它永远不会出现! 我不知道我是不是搞砸了,但你们应该看看。

    # its time for fetching data :)
   import csv
   import urllib2
   path = 'C:\\Users\\User\\Desktop\\Downloads\\'
   response = urllib2.urlopen('https://files.ontario.ca/opendata/births_by_year_and_month_per_place_of_event_city_2010_0.csv')
   html = response.read()

   file=open( path +"births.CSV", "r")
   reader = csv.reader(file)



   for row in reader:
       print row

   #Server Connection to MySQL:

   import MySQLdb
   conn = MySQLdb.connect(host= "localhost",
                     user="root",
                     passwd="admin",
                     db="cool")
   x = conn.cursor()

   try:
      x.execute("""INSERT INTO import (test) VALUES (%s,%s,%s,%s)""",(row))
      conn.commit()
   except:
      conn.rollback()

   conn.close()

它以退出代码0结束,打印所有内容,但从不插入数据库。 这是印刷品的样本

['2010', 'Sep', 'THUNDER BAY', '132']
['2010', 'Sep', 'TIMMINS', '59']
['2010', 'Sep', 'TORONTO', '3412']
['2010', 'Sep', 'WELLAND', '58']
['2010', 'Sep', 'WELLINGTON NORTH', '6']
['2010', 'Sep', 'WINDSOR', '337']
['2010', 'Sep', 'WOODSTOCK', '50']

Process finished with exit code 0

修改 我不确定%s部分是否与它有关,但我需要帮助。谢谢!

编辑2 大!感谢所有帮助过我的人。 但现在有一个新的编辑,我似乎无法找出问题出在哪里。 这是新代码!

     import csv
     import urllib2
     path = 'C:\\Users\\hongyu\\Desktop\\Downloads\\'
     response =  urllib2.urlopen('https://files.ontario.ca/opendata/births_by_year_and_month_per_ place_of_event_city_2010_0.csv')
     html = response.read()

     file=open( path +"births.CSV", "r")
     reader = csv.reader(file)
     #Server Connection to MySQL:

     import MySQLdb
     conn = MySQLdb.connect(host= "localhost",
                       user="root",
                       passwd="admin",
                       db="cool")

     for row in reader:
         x = conn.cursor()

         try:
             x.execute("""INSERT INTO testing (year, month, city, num)          VALUES (%s,%s,%s,%s)""", (row))
             conn.commit()
         except :
            conn.rollback()
             print(row)
             print("This row failed to insert")

     conn.close()

现在,当我运行代码时,它会告诉我哪些行无法插入。 但是有很多行失败了。 这是一些结果。

  ['1994', 'Dec', 'KAPUSKASING', '10']
  This row failed to insert
  ['1994', 'Dec', 'KENORA', '29']
  This row failed to insert
  ['1994', 'Dec', 'KINCARDINE', '11']
  This row failed to insert
  ['1994', 'Dec', 'KINGSTON', '198']
  This row failed to insert
  ['1994', 'Dec', 'KIRKLAND LAKE', '13']
  This row failed to insert
  ['1994', 'Dec', 'KITCHENER', '363']
  This row failed to insert
  ['1994', 'Dec', 'LEAMINGTON', '31']
  This row failed to insert  

有任何帮助吗?数据库几乎缺少一切,这里有一点点。 http://prntscr.com/h6dhod P.S:不仅仅是以a开头的城市,还有多伦多。

3 个答案:

答案 0 :(得分:0)

由于您尝试插入4个值,因此列列表中需要有4个列名称。

  x.execute("""INSERT INTO import (year, month, city, num) VALUES (%s,%s,%s,%s)""",(row))

将列名替换为表中的实际列。

这一行需要在for row in reader:循环内部,这应该在你打开MySQL连接之后。否则,您只需插入文件的最后一行。

答案 1 :(得分:0)

我建议你考虑在这里使用MySQL LOAD DATA

conn = MySQLdb.connect(host= "localhost",
                 user="root",
                 passwd="admin",
                 db="cool")
cursor = conn.cursor()
query = "LOAD DATA INFILE '/path/to/your/file.csv' INTO TABLE import FIELDS TERMINATED BY ',' ENCLOSED BY '\"' ESCAPED BY '\\\\'"
cursor.execute( query )
conn.commit()

这将需要担心正确的列数,并且还应该比执行许多插入语句好得多。

答案 2 :(得分:-2)

请理解CSV =逗号分隔值。 你需要先爆炸它。

$item = explode(",",$row);   //which will give you the array

并且在你的插入中你可能会使用$ item [0],$ item [1]等等