如何在屏幕(而不是文件)上以 CSV 格式输出 MySQL 查询结果并显示它?
要以 CSV 格式获得 MySQL 查询结果输出,请使用 concat()。语法如下 −
mysql> select concat(StudentId,',',StudentName,',',StudentAge) as CSVFormat from CSVFormatOutputs;
为了理解上述语法,让我们创建一个表格。创建表格的查询如下 −
mysql> create table CSVFormatOutputs -> ( -> StudentId int not null auto_increment, -> StudentName varchar(20), -> StudentAge int, -> PRIMARY KEY(StudentId) -> ); Query OK, 0 rows affected (1.15 sec)
使用 insert 命令在表格中插入一些记录。查询如下 −
mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('Mike',23);
Query OK, 1 row affected (0.26 sec)
mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('John',26);
Query OK, 1 row affected (0.19 sec)
mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('Sam',19);
Query OK, 1 row affected (0.20 sec)
mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('Carol',27);
Query OK, 1 row affected (0.59 sec)
mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('Bob',24);
Query OK, 1 row affected (0.15 sec)使用 select 语句显示表格中的所有记录。查询如下 −
mysql> select *from CSVFormatOutputs;
以下是输出 −
+-----------+-------------+------------+ | StudentId | StudentName | StudentAge | +-----------+-------------+------------+ | 1 | Mike | 23 | | 2 | John | 26 | | 3 | Sam | 19 | | 4 | Carol | 27 | | 5 | Bob | 24 | +-----------+-------------+------------+ 5 rows in set (0.00 sec)
以下是使用 contact() 方法以 CSV(逗号分隔值)格式输出结果的 MySQL 查询 −
mysql> select concat(StudentId,',',StudentName,',',StudentAge) as CSVFormat from CSVFormatOutputs;
以下是显示 CSV 格式记录的输出 −
+------------+ | CSVFormat | +------------+ | 1,Mike,23 | | 2,John,26 | | 3,Sam,19 | | 4,Carol,27 | | 5,Bob,24 | +------------+ 5 rows in set (0.00 sec)
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP