您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

将SQL信息写入TXT文件

将SQL信息写入TXT文件

这是一个可以正常工作并清理干净的版本。它摆脱了引起问题的更广泛的范围变量。它使用一种方式写入生成文件文件,因此您不必检测它是否已经存在。它将您的ROW1重命名为ROW2到实际上是它们的列。而且,它使您不必在每次写一行时都打开/关闭文件

   static void Main(string[] args)
    {
        string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string dbFile = filePath + @"\sqlfile.txt";

        writeFileFromDB(dbFile);
    }

    public static void writeFileFromDB(string dbFile)
    {
        //create connection
        sqlCommand comm = new sqlCommand();
        comm.Connection = new sqlConnection(@"MY DB CONNECTION STRING");
        String sql = @"SELECT COLUMN1, COLUMN2
                       FROM Export.TABLENAME";

        comm.CommandText = sql;
        comm.Connection.open();

        sqlDataReader sqlReader = comm.ExecuteReader();

        // Open the file for write operations.  If exists, it will overwrite due to the "false" parameter
        using (StreamWriter file = new StreamWriter(dbFile, false))
        {
            while (sqlReader.Read())
            {
                file.WriteLine(sqlReader["COLUMN1"] + "\t" + sqlReader["COLUMN2"]);
            }
        }

        sqlReader.Close();
        comm.Connection.Close();
    }
SQLServer 2022/1/1 18:51:01 有425人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶