Let's assume you want to store the output in a subdirectory to make it easier to manage e.g. ./my_script_data/
inside the secure folder, but you might run this script on multiple servers, possibly with different secure directories.
Firstly, for each server, set the secure_file_priv
to the most appropriate directory, perhaps on another drive e.g. X:/mysql_secure
. Do this by modifying the my.ini
file (create a backup first), searching for secure-file-priv
and providing an absolute path:
secure-file-priv="X:/mysql_secure"
NOTE: Make sure to save your file in the same encoding that it was originally written in (usually UTF-8). If you do not, the MySQLxx service will not start.
In your SQL script, store your output directory in a variable, using CONCAT()
to append other file paths as needed (they will have to be created manually before executing, unfortunately). That means the following path must already exist: X:/mysql_secure/my_script_data/
To create a timestamped CSV file with your output use the following:
-- ## VARIABLES
SET @stamp = DATE_FORMAT(NOW(), '%Y-%m-%d_%H%i%s');
SELECT CONCAT(@@GLOBAL.secure_file_priv, 'my_script_data/') INTO @outdir;
-- @@GLOBAL.secure_file_priv in Windows returns a path with '\'
-- hence our need to replace '\' with '/'
SET @outdir = REPLACE(@outdir, '\\', "/");
-- ## STATEMENT EXECUTION
SET @statement := CONCAT("SELECT * FROM my_database.table WHERE conditions INTO OUTFILE '",@outdir,"my_file_prefix_", @stamp, "_suffix.csv'");
PREPARE extrct FROM @statement;
EXECUTE extrct;
DEALLOCATE PREPARE extrct;
This produces a file: X:/mysql_secure/my_script_data/my_file_prefix_2021-05-24_190827_suffix.csv
.
I omitted field terminations, enclosures, and line terminations because they were the default values. These could be inserted into the @statement
variable if needed.
This was tested using Windows 10 and Windows Server 2016, both running MySQL 8.0.x.