【问题标题】:Importing csv file in mysql在mysql中导入csv文件
【发布时间】:2013-07-24 22:30:18
【问题描述】:

我有一个包含表格的数据库:人员、球员、教练和球队。所有表都有一个自动递增的 id 字段作为主键。人有 id、firstname、lastname。 Player 和 coach 都有 id 字段,以及 person_id 和 team_id 作为外键,以将它们绑定到其他表中的 team.id 或 person.id 字段。 我有一个主 csv 文件,我想从中导入 MySql 不同表中的所有值和 id。 我还想检查数据库中的值。如果该值在数据库中,则不要导入该值。 我使用了 CSV 解析和索引功能。但我无法做到这一点。任何人都可以帮助我吗 下面是我的sql表

mysql> describe person;
+-----------+-------------+------+-----+---------+----------------+
| Field     | Type        | Null | Key | Default | Extra          |
+-----------+-------------+------+-----+---------+----------------+
| id        | int(11)     | NO   | PRI | NULL    | auto_increment |
| firstname | varchar(30) | NO   |     | NULL    |                |
| lastname  | varchar(30) | NO   |     | NULL    |                |
+-----------+-------------+------+-----+---------+----------------+
mysql> describe player;
+-----------+---------+------+-----+---------+----------------+
| Field     | Type    | Null | Key | Default | Extra          |
+-----------+---------+------+-----+---------+----------------+
| id        | int(11) | NO   | PRI | NULL    | auto_increment |
| person_id | int(11) | NO   | MUL | NULL    |                |
| team_id   | int(11) | NO   | MUL | NULL    |                |
+-----------+---------+------+-----+---------+----------------+
mysql> describe team;
+-----------+-------------+------+-----+---------+----------------+
| Field     | Type        | Null | Key | Default | Extra          |
+-----------+-------------+------+-----+---------+----------------+
| id        | int(11)     | NO   | PRI | NULL    | auto_increment |
| teamname  | varchar(25) | NO   |     | NULL    |                |
| location  | varchar(40) | NO   |     | NULL    |                |
| city      | varchar(25) | NO   |     | NULL    |                |
| state     | varchar(2)  | NO   |     | NULL    |                |
| venue     | varchar(35) | NO   |     | NULL    |                |
| league_id | int(11)     | NO   | MUL | NULL    |                |
+-----------+-------------+------+-----+---------+----------------+

我的 CSV 文件是 名 姓 队名 地点 城市 州 |venue
abc cdf 印度 csv bng kar abc

导入后

我有一个包含表格的数据库:人员、球员、教练和球队。所有表都有一个自动递增的 id 字段作为主键。人有 id、firstname、lastname。 Player 和 coach 都有 id 字段,以及 person_id 和 team_id 作为外键,以将它们绑定到其他表中的 team.id 或 person.id 字段。 我有一个主 csv 文件,我想从中导入 MySql 不同表中的所有值和 id。 我还想检查数据库中的值。如果该值在数据库中,则不要导入该值。 我使用了 CSV 解析和索引功能。但我无法做到这一点。任何人都可以帮助我吗 下面是我的sql表

mysql> describe person;

+-----------+-------------+------+-----+---------+----------------+
| Field     | Type        | Null | Key | Default | Extra          |
+-----------+-------------+------+-----+---------+----------------+
| id        | int(11)     | NO   | PRI | NULL    | auto_increment |
| firstname | varchar(30) | NO   |     | NULL    |                |
| lastname  | varchar(30) | NO   |     | NULL    |                |
+-----------+-------------+------+-----+---------+----------------+
mysql> describe player;
+-----------+---------+------+-----+---------+----------------+
| Field     | Type    | Null | Key | Default | Extra          |
+-----------+---------+------+-----+---------+----------------+
| id        | int(11) | NO   | PRI | NULL    | auto_increment |
| person_id | int(11) | NO   | MUL | NULL    |                |
| team_id   | int(11) | NO   | MUL | NULL    |                |
+-----------+---------+------+-----+---------+----------------+
mysql> describe team;
+-----------+-------------+------+-----+---------+----------------+
| Field     | Type        | Null | Key | Default | Extra          |
+-----------+-------------+------+-----+---------+----------------+
| id        | int(11)     | NO   | PRI | NULL    | auto_increment |
| teamname  | varchar(25) | NO   |     | NULL    |                |
| location  | varchar(40) | NO   |     | NULL    |                |
| city      | varchar(25) | NO   |     | NULL    |                |
| state     | varchar(2)  | NO   |     | NULL    |                |
| venue     | varchar(35) | NO   |     | NULL    |                |
| league_id | int(11)     | NO   | MUL | NULL    |                |
+-----------+-------------+------+-----+---------+----------------+

我的 CSV 文件是

First Name  Last Name   teamname    Location    city    state   |venue  
abc cdf india   csv bng kar abc

导入后

id First Name   Last Name   teamname    Location    city    state   |venue  coment
1   1   1   1   1   1   1 abc abc

我正在尝试一些小代码

 # initialize with empty ints and dicts
        name,cities,countries,states=[],[],[],[]

        with open('ind.csv','rb') as csvfile:
            reader = csv.reader(csvfile, delimiter=',')
            reader.next() #skip header
            for row in reader:
                name.append(row[0])
                cities.append(row[2])
                states.append(row[3])
                countries.append(row[4])
        cl = list(set(countries))
        sl = list(set(states))
        citl = list(set(cities))
        inf1 = list(set(name)) 



        with open('countries.csv','w') as cfile:
            writer = csv.writer(cfile, delimiter=',')
            writer.writerow(['country_id','name'])
            for i,x in enumerate(cl):
                writer.writerow([i,x])

        with open('state.csv','w') as cfile:
            writer = csv.writer(cfile, delimiter=',')
            writer.writerow(['state_id','country_id','state'])
            for i,x in enumerate(sl):
                writer.writerow([i,x,cl.index(countries[states.index(x)])])

        with open('cities.csv','w') as cfile:
            writer = csv.writer(cfile,delimiter=',')
            writer.writerow(['city_id','city','st_id','country_id'])
            for i,x in enumerate(citl):
                writer.writerow([i,x,sl.index(states[cities.index(x)]),
                                 cl.index(countries[cities.index(x)])
                                 ])


        with open('inf123.csv','w') as cfile:
            writer = csv.writer(cfile,delimiter=',')
            writer.writerow(['Name_id', 'Name','city_id','st_id','country_id'])
            for i,x in enumerate(inf1):
                writer.writerow([i,x,
                                citl.index(cities[name.index(x)]),
                                sl.index(states[name.index(x)]),
                                cl.index(countries[name.index(x)])

                                 ])

        import MySQLdb 
        import csv
        mydb = MySQLdb.connect(host="localhost", # The Host 
        user="root", # username 
        passwd="root", # password 
        db="abcm") # name of the data base


        cursor = mydb.cursor()

        csv_data = csv.reader(file('countries.csv'))
        for row in csv_data:

            cursor.execute('INSERT INTO country(id, \
                  name )' \
                  'VALUES("%s", "%s")', 
                  row)
        #close the connection to the database.
        mydb.commit()
        cursor.close()
        print "Done"


        cursor = mydb.cursor()

        csv_data = csv.reader(file('state.csv'))
        for row in csv_data:

            cursor.execute('INSERT INTO state(id, \
                  country, name )' \
                  'VALUES("%s", "%s", "%s")', 
                  row)
        #close the connection to the database.
        mydb.commit()
        cursor.close()
        print "Done"    

【问题讨论】:

  • 为什么这条蟒蛇被标记在这里?
  • 您已将其标记为 Python,但未包含任何 Python 代码。用你尝试过但不起作用的方法更新它。

标签: python mysql


【解决方案1】:

我有一个主 csv 文件,我想从中导入所有值 MySql不同的表有id。

这是不可能的,因为导入例程不知道您要将数据放在哪里。

如果您的主 csv 文件包含包含表名的列,那么您可以

  • 将 csv 文件导入到临时文件中
  • 使用不同的 sql 语句将数据移动到相应的表中

【讨论】:

  • 兄弟我做了一些事情,我已经分享了我的python代码。我可以在一张表中导入。但是当它转到第二个国家/地区表时,它会显示错误。如果你运行它就会看到我的代码
猜你喜欢
  • 1970-01-01
  • 2016-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-04
  • 1970-01-01
  • 2017-03-03
相关资源
最近更新 更多