简体   繁体   English

将 csv 文件加载到 MySql 中的 Python 3.4 代码

[英]Python 3.4 code to load a csv file into MySql

I am new to Python and I am using python 3.4 and would like to write a script to load data from a csv file(with just 2 cols- emp_id, emp_name) into a MySQL DB table.我是 Python 新手,我正在使用 python 3.4,想编写一个脚本来将数据从 csv 文件(只有 2 个 cols-emp_id、emp_name)加载到 MySQL 数据库表中。 Anybody have sample code?有人有示例代码吗? Please help.请帮忙。

You don't need Python for that.您不需要为此使用 Python。 You don't even need a program for that.你甚至不需要一个程序。 MySQL has a statement for reading CSV files. MySQL 有一个用于读取 CSV 文件的语句。

See: https://dev.mysql.com/doc/refman/5.1/en/load-data.html , from the documentation:请参阅: https : //dev.mysql.com/doc/refman/5.1/en/load-data.html ,来自文档:

LOAD DATA INFILE can be used to read files obtained from external sources. For
example, many programs can export data in comma-separated values (CSV) format,
such that lines have fields separated by commas and enclosed within double
quotation marks, with an initial line of column names. If the lines in such a
file are terminated by carriage return/newline pairs, the statement shown here
illustrates the field- and line-handling options you would use to load the file:

LOAD DATA INFILE 'data.txt' INTO TABLE tbl_name
  FIELDS TERMINATED BY ',' ENCLOSED BY '"'
  LINES TERMINATED BY '\r\n'
  IGNORE 1 LINES;

If the input values are not necessarily enclosed within quotation marks, use
OPTIONALLY before the ENCLOSED BY keywords.

Apart from that, MySQL also comes with a program called mysqlimport which can do that too.除此之外,MySQL 还附带了一个名为mysqlimport 的程序,它也可以做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM