MySQL import and export csv file

MySQL import and export csv file

Export csv file statement structure

select * from j_position_provice
into outfile 'C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/xx.csv'
FIELDS TERMINATED BY ','   
OPTIONALLY ENCLOSED BY '"'   
LINES TERMINATED BY '\r\n' 

Import scv file statement structure

load data infile 'C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/output2.csv' 
into table a_test 
FIELDS TERMINATED BY ','   
OPTIONALLY ENCLOSED BY ''   
LINES TERMINATED BY '\r\n'(code_id,name);

Precautions

1.secute-file-priv
ERROR 1290 (HY000): The MySQL server is running with the –secure-file-priv option so it cannot execute this statement
When exporting csv, the above error may be thrown, which is due to insufficient permissions of the folder when exporting.
Method 1: We can query the permissions of the path on the command line or tools, the syntax is as follows
show variables like '%secure%'
Security query results
Find the path to secure_file_priv and use that directory in the INTO OUTFILE clause of our SELECT statement
SELECT * FROM xxxx WHERE XXX
INTO OUTFILE '/var/lib/mysql-files/report.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
Method 2: Find the location of the controllable secure folder
Find C:\ProgramData\MySQL\MySQL Server 5.7\my.ini and open it. We can find that after MySQL 5.6, secure-file-priv is a new version of MySQL A default value is added to the Server:
secure-file-priv=”C:/ProgramData/MySQL/MySQL Server 5.6/Uploads”
If you are in a non-production environment, you can try to modify it. Remember to restart the MySQL service after modification. At this time, we Put the files you need to import into this directory, and you can import them. I installed MySQl Server version 5.7, so my corresponding import statement is as follows:
select * from j_position_provice
into outfile 'C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/xx.csv'
FIELDS TERMINATED BY ','   
OPTIONALLY ENCLOSED BY '"'   
LINES TERMINATED BY '\r\n' 
2. When importing a file, the name of the file and the name of the database table should be as consistent as possible
If the database has multiple fields, and some of them are not used, you can write the specific fields in the import statement to match the csv columns and table fields
load data infile 'C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/a_position.csv' into table a_position 
    FIELDS TERMINATED BY ','   
    OPTIONALLY ENCLOSED BY '"'   
    LINES TERMINATED BY '\r\n'(code_id, name, parent_code_id);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325604269&siteId=291194637