三種重定向介紹
select ... into
使得mysql查詢結果能存儲在變量或者文件中:
-
select ... into var_list
使得查詢結果存儲在一個變量列表中 -
select ... into outfile
使得查詢結果存儲在一個文件中,同時可以指定列和行的終止符 -
select ... into dumpfile
使得單行結果寫入文件并不附帶任何格式化
測試數據建立
create table t(nValue int, Str varchar(100), bStr blob);
insert into t(nValue, Str, bStr) values(1, "szn", 0x1234), (2, "slz", 0xFFAA), (3, null, null);
輸出重定向到變量
? 輸出重定向到變量時箱季,變量的個數必須匹配select
列的個數唉堪,并且查詢結果必須有且只有一行(查詢結果為空時米奸,會觸發(fā)代號為1329的warning
。查詢結果為多行時准浴,會觸發(fā)代號為1172的error
)宿百。
select nValue, Str, bStr into @x, @y, @z from t limit 1;
select @x, @y, @z, hex(@z);
@x | @y | @z | hex(@z) |
---|---|---|---|
1 | szn | ?4 | 1234 |
輸出重定向到文件(outfile)
- 輸出重定向到文件時,這個文件是創(chuàng)建在server端的
- 重定向的輸出文件在指定的路徑上必須不存在
- my.ini文件中的
secure_file_priv
會影響導出路徑的選擇
select * from t into outfile 'd:/1.txt';
--上述查詢結果:[Err] 1290 - The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
--上述語句執(zhí)行失敗原因及解決方案下文將進行解釋
select * from t into outfile 'C:\\ProgramData\\MySQL\\MySQL Server 8.0\\Uploads\\1.txt';
--生成的文件內容(16進制顯示):31 09 73 7A 6E 09 12 34 0A 32 09 73 6C 7A 09 FF AA 0A 33 09 5C 4E 09 5C 4E 0A
重定向路徑
? 在之前查詢時感论,之所以第一次失敗而第二次成功的原因是my.ini
中指定了secure-file-priv="C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\"
,這就導致了重定向的路徑前綴必須是指定的值紊册”纫蓿可以修改此變量的值secure-file-priv=""
并重啟mysql服務,再次執(zhí)行即可成功:
select * from t into outfile 'd:/1.txt';
--受影響的行: 3
show variables like 'secure_file_priv';
--上述語句可用于查看my.ini中secure_file_priv的設定值
終止符設定
列終止符設定:fields TERMINATED by
行終止符設定:lines TERMINATED by
select * from t into outfile 'd:/1.txt' fields TERMINATED by ',' lines TERMINATED by '\r\n';
--輸出文件內容(16進制顯示):31 2C 73 7A 6E 2C 12 34 0D 0A 32 2C 73 6C 7A 2C FF AA 0D 0A 33 2C 5C 4E 2C 5C 4E 0D 0A
輸出重定向到文件(dumpfile)
select * from t limit 1 into DUMPFILE 'd:/1.txt';
--輸出文件內容(16進制顯示):31 73 7A 6E 12 34
select * from t limit 1, 1 into DUMPFILE 'd:/1.txt';
--輸出文件內容(16進制顯示):32 73 6C 7A FF AA
select * from t limit 2, 1 into DUMPFILE 'd:/1.txt';
--輸出文件內容(16進制顯示):33 00 00
參考資料: