How to export a CSV file from the MySQL command line
Comma-separated value files ( CSV ) are a way to transfer data between applications. Databases such as MySQL and spreadsheet software such as Excel both support importing and exporting via CSV , so we can use CSV files to exchange data between the two.
CSV files are plain text, so they are naturally lightweight and easy to export from MySQL.
Export from the database server
If we have access to a server running MySQL, we can INTO OUTFILE
export the selection using the command.
SELECT id, column1, column2 FROM table
INTO OUTFILE '/tmp/mysqlfiles/table.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY 'n'
This will output the CSV file to /tmp/mysqlfiles/table.csv , or wherever we configured it to go. We need to make sure that the user that runs MySQL (usually mysql or root) has ownership and write permissions to that directory.
We also need to make sure that
secure_file_priv
the settings allow MySQL to access this directory. By default, this blocks read and write access for SQL queries. This is a good thing; if our code is vulnerable toSQL
injection, any potential attacker will only have access to MySQL and not the rest of the file system.
We can whitelist specific directories by editing the MySQL configuration file (usually located at /etc/my.cnf ), including:
[mysqld]
secure-file-priv = "/tmp/mysqlfiles"
This will allow MySQL to read and write to /tmp/mysqlfiles/ (which we had to mkdir
create using ). Once MySQL can export files, we should be able to run queries and output a CSV file.
With ENCLOSED BY
the setting, commas will be escaped correctly, for example:
"3","Escape, this","also, this"
We can import this directly into any spreadsheet program or other software.
请记住
, the exported CSV file does not contain column headers, but the columns areSELECT
in the same order as the statement. Also, null values are exported as N, which is the expected behavior, but if we want to change this, we can modify the selection by enclosing around the fields inSELECT
the statement .ifnull(field, "")
Exporting from the MySQL command line
If we only have access to the MySQL instance through the command line, and not to the server itself (such as when it is not managed by us, in the case of Amazon RDS), the problem is a bit tricky. Although we can use on the server FIELDS TERMINATED BY ','
to generate a comma-delimited list, the MySQL CLI will use tab delimiters by default.
Simply enter the query from the command line and pipe it to the file:
$ mysql -u root -e "select * from database;" > output.tsv
Because MySQL output is tab-delimited, it is called a TSV file, which stands for "Tab Separated Values," and can be used in place of a CSV file in some programs (such as spreadsheet import). But it is not a CSV file, and converting it to a CSV file is complicated.
We could simply replace each tab with a comma, which would work, but would fail if there were commas in the input data. If we are absolutely 100%
sure that there are no commas in the TSV file ( grep
check with ), we can replace the tabs with sed
(see our sed tutorial for this command):
$ sed "s/t/,/g" output.tsv > output.csv
But if your data has commas in it, you'll have to use a longer regular expression:
$ sed "s/'/'/;s/t/","/g;s/^/"/;s/$/"/;s/n//g" output.tsv > output.csv
This will correctly escape the quoted fields, thus solving the comma issue.
注意
: The tab character t is not standard. On macOS and BSD, it is not available, which causes each lowercase "t" to be mangled, resulting insed
incorrect commas being inserted. To fix this, we need to use a literal tab character insteadt
:
sed "s/ /,/g" output.tsv > output.csv
If our input data contains tab characters, we are out of luck and must generate a CSV file ourselves using a scripting language.
Do it manually using a real programming language
MySQL (and most databases) are designed to be interacted with, so we probably already have some programming language connected to MySQL. Most languages can also write to disk, so we can create our own CSV output script by reading the fields directly from the database, escaping them properly, and then writing a comma-delimited file.
Related Reading
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Two ways to install mysql-5.5.47 on Linux system and manage mysql
Publish Date:2025/04/26 Views:140 Category:MySQL
-
We know that there are generally two ways to install software on the Linux system. One is to use rpm or yum to install, which is convenient and fast; the other is to use the compiled source package. Although this method is more troublesome
Mysql master-slave replication simple configuration
Publish Date:2025/04/26 Views:120 Category:MySQL
-
I'm learning about MySQL master-slave replication recently and want to apply it to a project at work. Since I'm new to it, I don't understand it very well, so I can only share how to make a simple configuration. At the beginning, we configu
Implementation details of MySQL master-slave replication (I) Exploration of the m
Publish Date:2025/04/26 Views:56 Category:MySQL
-
This article mainly discusses the implementation mechanism of master-slave replication, which may not be directly helpful for our actual application, but understanding its principle can achieve twice the result with half the effort for futu
Implementation details of MySQL master-slave replication (II) Exploration from th
Publish Date:2025/04/26 Views:74 Category:MySQL
-
Previously we explored the master server in master-slave replication. Now let's look at how the slave server works in the entire system. In the article Master Server Exploration, we mentioned that three threads are needed in a master-slave
Mysql master-slave replication - what to do if the slave server stops
Publish Date:2025/04/26 Views:97 Category:MySQL
-
You may find this topic a little ridiculous. What can we do if the server stops? Of course, we should restart the service. Restarting the service is no problem. The problem is that a lot of data has been written to the master database durin
MySQL stored procedure details
Publish Date:2025/04/26 Views:163 Category:MySQL
-
A stored procedure can be thought of as encapsulating a SQL statement that we need to process specially into a function. When needed, we only need to call this function to achieve the desired operation. This process can be called a stored p
How many of these MySQL statement tags have you used?
Publish Date:2025/04/26 Views:122 Category:MySQL
-
In the article "A Peek into MySQL Stored Procedure Details" , we briefly introduced the use of stored procedures. The syntax for creating stored procedures includes BEGIN...END. In addition to BEGIN...END, the following statement tags can b
MySQL CURRENT_TIMESTAMP() Function Detailed Introduction (with Examples)
Publish Date:2025/04/26 Views:132 Category:MySQL
-
This article explains how to use MySQL functions with examples CURRENT_TIMESTAMP() . By using it, we can convert or display the current date and time. The output format is "YYYY-MM-DD HH:MM:SS" or "YYYYMMDDHHMMSS", depending on the context
Back up the MySQL database to a file
Publish Date:2025/04/26 Views:166 Category:MySQL
-
Backing up your database is a very important system administration task that should usually cron be run from a job at scheduled intervals. We will use mysqldump the dump utility that comes with mysql to dump the contents of the database to