INTO OUTFILE 使用执行语句

INTO OUTFILE using Execute Statement

我需要从 mysql 数据库中获取数据。我有以下内容:

set @filename=concat('/home/reports/',current_timestamp(),'.csv');
set @querys=concat("select * from  tablename limit 10 ",
"into outfile ? fields terminated by ',';");
prepare s1 from @querys;
execute s1 using @filename;
deallocate prepare s1;

我收到了这个错误:错误代码:1064。您的 SQL 语法有误;查看与您的 MySQL 服务器版本对应的手册,了解在 '? 附近使用的正确语法。在第 1 行以“,”结尾的字段
你知道为什么吗?

我非常怀疑 MySQL 是否支持在 insert into outfile 语法中将查询字符串作为参数传递。您需要改为进行字符串连接。引用文件名也是个好主意,因为它将包含空白字符。

set @filename = concat('/home/reports/', current_timestamp(), '.csv');

set @query=
    concat(
        "insert into outfile '", 
        @filename, 
        "' select * from  tablename limit 10 ",
       "fields terminated by ',';"
    );

prepare s1 from @query;
execute s1;
deallocate prepare s1;

我认为你的查询语法有误,应该是

SELECT * INTO OUTFILE '/tmp/USERS.csv' from users FIELDS TERMINATED BY ',' ENCLOSED BY '"' limit 10;

还要检查以下提到的路径位置:

mysql> SELECT @@secure_file_priv;