C#将sql查询写入文件吗?

问题描述 投票:0回答:3

我想将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 save streamwriter
3个回答
0
投票

我找到了一种方法:

file.WriteLine("{0},{1}", queryReader["ordrenr"], queryReader["user"]);

0
投票
        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(),还需要最后关闭文件。不在第一次迭代中!


0
投票

我现在意识到已经六岁了,但是当我在自己的搜索中遇到这个问题时,我觉得提供一个更简洁的答案对其他人也将是一件好事。另外,我还不能发表评论,所以我认为我最好把它作为答案提交。

OP的答案提出了一个非常主要的性能问题,即每行重新创建流,正如Magus在评论中指出的。

同时,mybirthname的答案实际上永远不会以添加标题行结尾,并且如果在创建时将包含的布尔值更改为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();

[根据Magus的建议,如果您想改用Using语句(这可能是个好主意,您也可以像这样构造它:

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"]);
                }
            }    
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.