简体   繁体   中英

How to bulk copy sql (export) tables to a csv or tsv files in .Net?

Are there any .Net libraries that provide a way of exporting sql database data to plain text files (ie csv\\tsv)? SqlBulkCopy only applies to the import part of the solution and I prefer not to be calling any Process.Start calls to open up command prompts to call bcp.exe.

Check out FileHelpers - it allows you to easily load or save data from CSV or other text file formats. Excellent code base, freeware, full C# source available - can't recommend it enough!

不幸的是,使用bcp Process调用结束了

Here's a code snippet for what JK was saying:

System.Diagnostics.Process p = new System.Diagnostics.Process();             
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "BCP.exe";
p.StartInfo.Arguments = "\"SELECT * FROM DATABASENAME.dbo.TABLENAME\" queryout \"FILENAME.txt\" -S \"SEVERNAMEHERE\" -U USERNAME -P PASSWORD -c -k";
p.Start(); 
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();

As such there is no .net library which you can use for export data into txt/csv. You can use StreamWriter to write data in txt/csv file.

Would calling a stored procedure work for you? I did a quick Google for using bulk copy in a procedure and found this article:

http://www.simple-talk.com/sql/database-administration/creating-csv-files-using-bcp-and-stored-procedures/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM