📜  sql server 自动查询输出到 json 文件 - C# 代码示例

📅  最后修改于: 2022-03-11 14:49:02.981000             🧑  作者: Mango

代码示例1
// TODO: Add your code here
                string query = "SELECT TOP 5 [BusinessEntityID],[NationalIDNumber],[OrganizationNode],[OrganizationLevel] FROM [HumanResources].[Employee]";
                string connectionSql = "Server=(local);Database=AdventureWorks2016CTP3;Integrated Security=true";
                StreamWriter myFile = new StreamWriter(@"c:\sql\fileCSharp.txt");
                using (SqlConnection connection = new SqlConnection(connectionSql))
                {
                    SqlCommand command = new SqlCommand(query, connection);
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    try
                    {
                        while (reader.Read())
                        {
                            myFile.WriteLine(String.Format("{0}, {1}, {2}, {3}", 
                            reader["BusinessEntityID"], reader["NationalIDNumber"], reader["OrganizationNode"], reader["OrganizationLevel"]));
                        }
                    }
                    catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                            Dts.TaskResult = (int)ScriptResults.Failure;
                        }
                    finally
                        {
                            reader.Close();
                            myFile.Close();
                        }
                }