【问题标题】:How to create a .txt file and insert data into it in SQL?如何在 SQL 中创建 .txt 文件并将数据插入其中?
【发布时间】:2020-04-01 12:52:13
【问题描述】:

我正在学习触发器和事件,但遇到以下问题:

我创建了一个触发器,当在表 movie 中进行更新时,它会将数据插入到名为 updated_movie 的表中。

另外,我想创建一个每天上午 11:30 执行的事件,该事件创建一个文本文件,其中包含表 updated_movie 中的一些数据。到目前为止,我已经做到了:

delimiter !!
drop event if exists createFile !!
create event createFile on schedule at "11:30"

do begin

    declare path varchar(255) default "/Users/Shared/BDD/L19/";
    declare nameFile varchar(255) default curdate();
    declare done int default 0;
    declare t varchar(255);

    -- creation of the text file?

    declare c cursor for select title from updated_movie;
    declare continue handler for not found set done = 1;

    open c;

    l:loop
        fetch c into t;

        if done = 1 then
            leave l;
        end if;

        call copyIntoFile(t, nameFile);

    end loop l;

end!!

delimiter ;

这是我每天都想执行的事件。如何在事件中声明的路径中创建一个与声明的变量nameFile具有相同文件名的文本文件?

此外,到目前为止,过程 copyIntoFile 看起来像这样:

delimiter !!
drop procedure if exists copyIntoFile !!
create procedure copyIntoFile(in str varchar(255), in fileName varchar(255)

begin

    -- Copy into the text file?

end !!

delimiter ;

如何才能在文本字段中插入一些数据?

如果您想知道,updated_movie 表只有一个 varchar(255) 字段。

【问题讨论】:

标签: mysql sql file


【解决方案1】:
CREATE EVENT createFile 
ON SCHEDULE 
    EVERY 1 DAY
    STARTS CURRENT_DATE + INTERVAL '11:30' HOUR_MINUTE
ENABLE
DO
SELECT *
    INTO OUTFILE 'drive:\\folder\\filename.ext'
    FROM updated_movie
    WHERE created_at >= NOW() - INTERVAL 1 DAY;

根据需要修改条件、输出表达式、添加导出规范。

检查secure_file_priv 设置和相关设置,并相应地证明目标地址。需要文件权限。

PS。 BEGIN-END、DELIMITER 等 - 是多余的。

【讨论】:

  • 谢谢!它可能会起作用。现在我必须弄清楚如何更改secure_file_priv 设置。我正在使用 Mac 和 MySQLWorkbench,欢迎任何帮助!
  • 我必须弄清楚如何更改 secure_file_priv 设置 编辑 INI 文件。重启 MySQL。
猜你喜欢
  • 2018-03-25
  • 2016-03-09
  • 2021-03-27
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 2017-10-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多