gpt4 book ai didi

MySQL导出表到文本文件字段名称

转载 作者:行者123 更新时间:2023-11-29 07:37:32 24 4
gpt4 key购买 nike

假设我在 MySQL 中有下表

create table test_tbl
(
col1 varchar(100),
col2 varchar(100),
amount int,
created datetime
)

数据插入

Insert into test_tbl values('unu', 'doi', 10, '05/01/2015');
Insert into test_tbl values('patru', trei', 400, '04/01/2015');

我需要按以下格式导出该表中的所有数据。该文件应该是txt文件。

"col1"="unu","col2"="doi","amount"="10","created"="05/01/2015"
"col1"="patru","col2"="trei","amount"="400","created"="04/01/2015"

所以逻辑是:每个列名称及其值以逗号分隔。

MySQL中可能得到这样的结果吗?

最佳答案

用于导出表的数据-

SELECT  CONCAT('"col1"="',col1,'","col2"="',col2,'","amount"="',amount,'","created"="',DATE_FORMAT(created,'%d/%m/%Y'),'"') t  FROM test_tbl INTO OUTFILE '/tmp/test.txt' CHARACTER SET latin1 FIELDS ENCLOSED BY '' LINES TERMINATED BY '\r\n';

用于从 csv 导入表格

    mysql> CREATE TABLE `test_tbl` (
-> `col1` varchar(100) DEFAULT NULL,
-> `col2` varchar(100) DEFAULT NULL,
-> `amount` int DEFAULT NULL,
-> `created` datetime DEFAULT NULL
-> ) ENGINE=InnoDB DEFAULT CHARSET=latin1
-> ;
Query OK, 0 rows affected (0.44 sec)

mysql> load data local infile 'test.txt' into table test_tbl fields terminated by ',' ENCLOSED BY '"' lines terminated by '\r\n' (@col1, @col2,@col3,@col4)
-> set col1 = substr(@col1,8), col2 = substr(@col2,8), amount = substr(@col3,10), created = str_to_date(substr(@col4,11), '%d/%m/%Y');
Query OK, 2 rows affected (0.09 sec)
Records: 2 Deleted: 0 Skipped: 0 Warnings: 0

mysql> select * from test_tbl;
+-------+------+--------+---------------------+
| col1 | col2 | amount | created |
+-------+------+--------+---------------------+
| unu | doi | 10 | 2015-01-05 00:00:00 |
| patru | trei | 400 | 2015-01-04 00:00:00 |
+-------+------+--------+---------------------+
2 rows in set (0.00 sec)

关于MySQL导出表到文本文件字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30234909/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com