[英]How to export a csv file from a mysql server using a C# application and get all column names in the top of the exported csv-file
I looked for a similar question but didnt find a solution for my problem. 我寻找了类似的问题,但没有找到解决问题的方法。 I developed a C# program which communicates with a mysql server.
我开发了一个与mysql服务器通信的C#程序。
I try to export a table from the mysql server to a csv file including the names of each column in the top. 我尝试将表从mysql服务器导出到csv文件,其中包括顶部各列的名称。 It's working, but theres a problem.
它正在工作,但是有问题。 When I use the following code:
当我使用以下代码时:
string query = "SELECT /*here i insert column names*/
UNION SELECT /*here i insert column names*/
FROM `tableName` INTO OUTFILE /*here I insert the path*/
\ FIELDS TERMINATED BY ';' LINES TERMINATED BY '\n'";
It works, but I have to write each column. 它有效,但是我必须写每一列。 Is there a possibility to avoid that?
有可能避免这种情况吗? So I could use the * operator so it looks like:
所以我可以使用*运算符,使其看起来像:
string query = "SELECT *
UNION SELECT *
FROM `tableName` INTO OUTFILE /*here I insert the path*/
\ FIELDS TERMINATED BY ';' LINES TERMINATED BY '\n'";
Because this Code is not working for me. 因为此代码对我不起作用。
You can get all column names from your table with following statement: 您可以使用以下语句从表中获取所有列名称:
SELECT COLUMN_NAME, ORDINAL_POSITION FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Bundle'
Export your rows -> Get all column names using above statement -> Write your result to the beginning of your file using C# 导出行->使用上述语句获取所有列名->使用C#将结果写入文件的开头
This is how I would do this. 这就是我要做的。 Another possibility is a dynamic pivot which is much more complicated.
另一种可能性是动态枢轴,它要复杂得多。
EDIT 编辑
Since OP mentioned that he may not have access to the exported file, here is a quick and dirty statement achieving the wanted result: 由于OP提到他可能无权访问导出的文件,因此以下是快速而肮脏的语句,可达到所需的结果:
DECLARE @DataList varchar(500);
SELECT @DataList = COALESCE(@DataList + ',', '') + 'CAST(' + COLUMN_NAME + ' AS varchar(255))'
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'YOURTABLE'
DECLARE @PivotList varchar(500);
SELECT @PivotList = COALESCE(@PivotList + ',', '') + COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'YOURTABLE'
DECLARE @GroupList varchar(500);
SELECT @GroupList = COALESCE(@GroupList + ',', '') + 'MIN(CAST(' + COLUMN_NAME + ' AS varchar(255)))'
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'YOURTABLE'
DECLARE @Query varchar(1000)
SET @Query = '
SELECT ' + @GroupList + ' FROM INFORMATION_SCHEMA.COLUMNS
PIVOT
(MAX(COLUMN_NAME) FOR COLUMN_NAME IN (' + @PivotList + ')) AS B
WHERE TABLE_NAME = ''YOURTABLE''
GROUP BY TABLE_NAME
UNION ALL
SELECT ' + @DataList + ' FROM YOURTABLE'
EXEC (@Query)
I hope this works for you! 希望这对您有用!
Regards. 问候。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.