从SQL导出数据并写入etxt文件(可以使用无BCP或SP)

所以我正在寻找一种从SQL Server 2000数据库导出数据并将其写入逗号分隔文本文件的简单方法。 它的一个表只有大约1,000行。 我是C#的新手所以请原谅我这是一个愚蠢的问题。

这是一项非常简单的任务,但您需要学习SqlClient命名空间以及您可以使用的不同对象。 您需要注意的是,对于SQL Server 2000而言,不支持较低的异步方法,因此它们将全部阻塞。

请注意,这是一个非常粗略的例子,我没有对此进行测试,但这是一种通用的方法。

string connectionString = ""; using (SqlConnection connection = new SqlConnection(connectionString)) { try { connection.Open(); } catch (System.Data.SqlClient.SqlException ex) { // handle return; } string selectCommandText = "SELECT * FROM "; using (SqlDataAdapter adapter = new SqlDataAdapter(selectCommandText, connection)) { using (DataTable table = new DataTable("")) { adapter.Fill(table); StringBuilder commaDelimitedText = new StringBuilder(); commaDelimitedText.AppendLine("col1,col2,col3"); // optional if you want column names in first row foreach (DataRow row in table.Rows) { string value = string.Format("{0},{1},{2}", row[0], row[1], row[2]); // how you format is up to you (spaces, tabs, delimiter, etc) commaDelimitedText.AppendLine(value); } File.WriteAllText("", commaDelimitedText.ToString()); } } } 

您需要查看的一些资源:

我也不确定你的要求是什么,或者你为什么要做这个任务,但是也有很多工具可以为你做这个(如果这是一次性的事情),因为这不是一个不寻常的任务。

与使用您需要的工具的任何其他语言相比,这在C#中没有什么不同。

1)查询DB并将数据存储在集合中
2)以CSV格式将集合写入文件

你是在Windows窗体应用程序中这样做的吗? 如果已将数据绑定到控件(如DataGridView),则这很容易实现。 您可以循环访问控件并以这种方式编写文件。 我喜欢这个,因为如果你在应用程序中实现了过滤机制,那么无论用户过滤了什么都可以写入文件。 这就是我以前做过的。 如果你使用某种集合而没有太多麻烦,你应该能够调整它。

 private void exportCsv() { SaveFileDialog saveFile = new SaveFileDialog(); createSaveDialog(saveFile, ".csv", "CSV (*csv)|*.csv)"); TextWriter writer = new StreamWriter(saveFile.FileName); int row = dataGridView1.Rows.Count; int col = dataGridView1.Columns.Count; try { if (saveFile.FileName != "") { for (int i = 0; i < dataGridView1.Columns.Count; i++) { writer.Write(dataGridView1.Columns[i].HeaderText + ","); } writer.Write("\r\n"); for (int j = 0; j < row - 1; j++) { for (int k = 0; k < col - 1; k++) { writer.Write(dataGridView1.Rows[j].Cells[k].Value.ToString() + ","); } writer.Write("\r\n"); } } MessageBox.Show("File Sucessfully Created!", "File Saved", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } catch { MessageBox.Show("File could not be created.", "Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { writer.Close(); saveFile.Dispose(); } }