要将CSV文件导入到MySQL表中,我们必须有一个CSV文件,即其中包含逗号分隔值的文件。然后,我们必须具有相同名称和结构的MySQL表。为了说明这一点,我们采用以下示例-
例如,我们的Address.CSV文件包含以下数据-
名称,姓氏,地址
Mohan, Sharma, Sundernagar Saurabh, Arora, Chandigarh Rajesh, Singh, Lucknow
我们想将这些值导入具有以下结构的名为Address的MySQL表中-
mysql> DESCRIBE ADDRESS; +----------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+-------+ | Name | varchar(20) | YES | | NULL | | | LastName | varchar(20) | YES | | NULL | | | Address | varchar(20) | YES | | NULL | | +----------+-------------+------+-----+---------+-------+ 3 rows in set (0.00 sec)
现在,借助mysql import以及一些选项,我们可以将address.csv的值导入到名为“ address”的MySQL表中-
C:\mysql\bin>mysqlimport --ignore-lines=1 --fields-terminated-by=, --verbose --local -u root query C:/mysql/bin/mysql-files/address.csv Connecting to localhost Selecting database query Loading data from LOCAL file: C:/mysql/bin/mysql-files/address.csv into address query.address: Records: 3 Deleted: 0 Skipped: 0 Warnings: 0 Disconnecting from localhost mysql> Select * from Address; +---------+----------+-------------+ | Name | LastName | Address | +---------+----------+-------------+ | Mohan | Sharma | Sundernagar | | Saurabh | Arora | Chandigarh | | Rajesh | Singh | Lucknow | +---------+----------+-------------+ 3 rows in set (0.00 sec)
上面的结果集表明,CSV文件中的值已导入到MySQL表中。