在 MySQL 中创建数据并将数据添加到文本文件时出现问题?

Problem with creating and adding data into a text file in MySQL?

我创建了以下过程,使用两个不同的准备语句,将一些数据写入具有相同名称的文本文件中。

程序

delimiter !!
drop procedure if exists copyIntoFile !!
create procedure copyIntoFile()

begin
    declare path varchar(255);
    set path = concat("'C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/", curdate(), ".txt'");

    set @aux1 = concat("select * from movie_modification where modified = true into outfile ", path, 
                        " fields terminated by ';' lines starting by 'Edit: ' terminated by '\n';");
    prepare stmt1 from @aux1;
    execute stmt1;
    deallocate prepare stmt1;

    set @aux2 = concat("select * from movie_modification where modified = false into outfile ", path, 
                        " fields terminated by ';' lines starting by 'New: ' terminated by '\n';");
    prepare stmt2 from @aux2;
    execute stmt2;
    deallocate prepare stmt2;

    delete from movie_modification;
end !!
delimiter ;

当我执行此过程时,语句 aux1 正确执行并创建文本文件并将数据写入其中。但是当执行到第二条语句(aux2)时,我得到以下错误:

Error Code: 1086. File 'C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/2020-04-03.txt' already exists

出现此错误是因为文件已在语句 aux1.

中创建

我如何修改第二条语句 aux2 知道文件已经创建?

我不认为你可以要求 MySQL 追加到同一个文件,但你可以 UNION 两个查询。

您可以将 'Edit: ''New: ' 添加到查询中,从而允许您使用 UNION 将其减少为一个查询。

您可能需要更改查询以指定您想要的所有列 SELECT 'Edit: ',* 行不通,但这里有一个建议。

delimiter !!
drop procedure if exists copyIntoFile !!
create procedure copyIntoFile()

begin
    declare path varchar(255);
    set path = concat("'C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/", curdate(), ".txt'");

    set @aux = concat("select 'Edit: ', col1,col2 from movie_modification where modified = true
                    UNION ALL
                    select 'New: ', col1,col2 from movie_modification where modified = false
                 into outfile ", path, 
                 " fields terminated by ';' lines terminated by '\n';");

    prepare stmt from @aux;
    execute stmt;

    deallocate prepare stmt;
    delete from movie_modification;
end !!
delimiter ;