C#将sql查询写入文件

本文关键字:文件 查询 sql | 更新日期: 2023-09-27 18:24:38

我想将sql查询写入文件,但我只能在文本文件中写入查询的一列。如何添加更多列?

这是我的c#windows表单代码:

SqlConnection con = new SqlConnection(@"Data Source=" + globalvariables.hosttxt + "," + globalvariables.porttxt + "''SQLEXPRESS;Database=ha;Persist Security Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'");
SqlCommand command = con.CreateCommand();
command.CommandText = "Select * from bestillinger";
con.Open();
SqlDataReader queryReader = command.ExecuteReader();
while (queryReader.Read())
{
    StreamWriter file = new StreamWriter(@"C:'Users'Michael'Desktop'query.txt");
    file.WriteLine(queryReader["ordrenr"]);
    file.Close();
}
queryReader.Close();
con.Close();

它不允许我写:

file.WriteLine(queryReader["ordrenr"] + queryReader["user"]);

C#将sql查询写入文件

我意识到这已经六岁了,但当我在自己的搜索中发现这一点时,我觉得提供一个稍微干净一点的答案对其他人也有好处。此外,我还不能发表评论,所以我想我还不如提交这个作为答案。

正如Magus在评论中指出的那样,OP的回答提出了一个相当大的性能问题,即用每一行重新创建流。

同时,mybirthname的答案实际上永远不会添加标题行,如果在创建时包含的bool更改为true,那么它最终会生成一个只包含标题的文件。

在这种特殊情况下,我将以逗号分隔值格式写出数据。如果您以后想在电子表格编辑器中打开它,文件扩展名可以是.csv,如果不想被任何最终用户查看,则可以是.txt。

//Consider putting your connection string in a config file and referencing it here.
SqlConnection sqlConn = new SqlConnection(Properties.Settings.Default.ConnString);
//If possible, avoid using "Select *" and instead, select only the columns you care about to increase efficiency.
SqlCommand sqlCmd = new SqlCommand("Select ordrenr, user From bestillinger", sqlConn);
sqlConn.Open();
SqlDataReader sdr = sqlCmd.ExecuteReader();
if (sdr.HasRows)
{
    //There's really no reason to create the StreamWriter unless you actually find some data.
    StreamWriter swExportWriter = new StreamWriter(@"C:'DataStore'Datafile.csv");
    //Now that you know you have data, go ahead and write the first line to the file as the header row.
    swExportWriter.WriteLine("ordrenr, user");
    //Now use SqlDataReader.Read() to loop through the records and write each one to the file.
    while (sdr.Read())
    {            
        swExportWriter.WriteLine("{0},{1}", sdr["ordrenr"], sdr["user"]);
    }
    //Don't forget to close the StreamWriter!
    swExportWriter.Close();
}
sdr.Close();
sqlConn.Close();

如果你想使用Using语句,按照Magus的建议(这可能是个好主意),你也可以这样构建:

using (SqlConnection sqlConn = new SqlConnection(Properties.Settings.Default.ConnString))
{
    SqlCommand sqlCmd = new SqlCommand("Select ordrenr, user From bestillinger", sqlConn)
    sqlConn.Open();
    using (SqlDataReader sdr = sqlCmd.ExecuteReader())
    {
        if (sdr.HasRows)
        {        
            using (StreamWriter swExportWriter = new StreamWriter(@"C:'DataStore'Datafile.csv"))
            {
                swExportWriter.WriteLine("ordrenr, user");
                while (sdr.Read())
                {            
                    swExportWriter.WriteLine("{0},{1}", sdr["ordrenr"], sdr["user"]);
                }
            }    
        }
    }
}

我找到了一种方法:

file.WriteLine("{0},{1}", queryReader["ordrenr"], queryReader["user"]);
        static void Main(string[] args)
        {
            string connString = @"here connection string";
            SqlConnection con = new SqlConnection(connString);
            SqlCommand command = con.CreateCommand();
            command.CommandText = "Select * from Object";
            con.Open();
            SqlDataReader queryReader = command.ExecuteReader();
            StreamWriter file = new StreamWriter(@"C:'Projects'EverydayProject'test.txt");
            bool addColumns = false;
            string columnName1="Title";
            string columnName2 = "City"; 
            while (queryReader.Read())
            {
                if(addColumns)
                {
                     file.WriteLine(columnName1 + " " + columnName2);
                     addColumns = true;
                }
                else
                {
                     file.WriteLine(queryReader["Title"].ToString() + " " + queryReader["City"].ToString());
                }                      
            }
            queryReader.Close();
            con.Close();
            file.Close();
        }

这是有效的——你应该首先将对象制作成String()——你还需要在最后关闭文件。不是第一次迭代!