小编典典

将SQL信息写入TXT文件

sql

我试图从数据库中读取一行信息,并将其写到txt文件中。我已经弄清楚了,但是我收到以下错误“字段初始化程序无法引用非静态字段,方法或属性’reader_writer.filewriter.filePath’”,我不知道为什么。有人可以解释我的问题吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data.SqlClient;
using System.Data.Common;

namespace reader_writer
{
public class filewriter
{

    //public string filePath = "";
    bool fileExists = false;
    string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    string dbFile = filePath + @"\sqlfile.txt";

    public void Main(string[] args)
    {


        fileExists = File.Exists(dbFile);

        if (fileExists)
        {
            writeFileFromDB();
        }

        else
        {
            File.Create(dbFile);
            writeFileFromDB();
        }

    }


    public void writeFileFromDB()
    {
        //create connection
        SqlCommand comm = new SqlCommand();
        comm.Connection = new SqlConnection(@"MY DB CONNECTION STRING");
        String sql = @"SELECT ROW1, ROW2
                           FROM Export.TABLENAME";

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

        SqlDataReader sqlReader = comm.ExecuteReader();

        while (sqlReader.Read())
        {
            StreamWriter writer = File.CreateText(dbFile);
            writer.WriteLine(sqlReader["ROW1"] + "\t" + sqlReader["ROW2"]);
            writer.Close();
        }

        sqlReader.Close();
        comm.Connection.Close();
    }
}

}


阅读 359

收藏
2021-05-16

共1个答案

小编典典

这是一个可以正常工作并清理干净的版本。它摆脱了引起问题的更广泛的范围变量。它使用一种方式写入生成该文件的文件,因此您不必检测它是否已经存在。它将您的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();
    }
2021-05-16