如何从数据库中读取数据&;把它写在一个txt文件上

本文关键字:文件 txt 一个 数据库 读取 数据 amp | 更新日期: 2023-09-27 18:22:19

我想在文本文件上使用windows服务从服务器数据库检索数据?我能做到吗?我该怎么做?我的意思是,我知道创建一个窗口服务,但我对SQL连接和文件编写部分感到困惑,在哪里执行它?我试过

class Program
{
    static void Main(string[] args)
    {
        RunSchedule();
    }
    public static void RunSchedule()
    {
        string path = Path.GetFullPath("d:''MyTest") + "''" + DateTime.Now.ToString("MM_dd_yyyy_HH_mm") + "_Log.txt";
        try
        {

            if (!File.Exists(path))
            {
                File.Create(path);
                SqlConnection conn = new SqlConnection("Data Source=...;Initial Catalog=Test;User ID=s_a;Password=sa56ta112;");
                String sql = @"SELECT Id,UserName, Email,Password,CreatedDate
                  FROM Register";
                SqlCommand com = new SqlCommand();
                com.CommandText = sql;
                //com.Connection = conn;
                conn.Open();
                StreamWriter tw = File.AppendText("d:''MyTest");
                SqlDataReader reader = com.ExecuteReader();
                tw.WriteLine("Id,UserName,Email,Password,CreatedDate");
                while (reader.Read())
                {
                    tw.Write(reader["Id"].ToString());
                    tw.Write(" , " + reader["UserName"].ToString());
                    tw.Write(" , " + reader["Email"].ToString());
                    tw.Write(" , " + reader["Password"].ToString());
                    tw.Write(" , " + reader["CreatedDate"].ToString());
                }
                tw.WriteLine(DateTime.Now);
                tw.WriteLine("---------------------------------");
                tw.Close();
                reader.Close();
                conn.Close();
            }
        }
        catch (Exception ex)
        {
            string errorLogPath = @"D:'MyTest.txt";
            File.AppendAllText(errorLogPath, Environment.NewLine + ex.Message);
        }
    }
}

我做得对吗?请引导我。

如何从数据库中读取数据&;把它写在一个txt文件上

while (reader.Read())
{
    row = new DataRow();
    row.ItemArray = new object[reader.FieldCount];
    reader.GetValues(row.ItemArray);
    foreach (object item in row.ItemArray)
    {
        streamWriter.Write((string)item + "'t");
    }
    streamWriter.WriteLine();
}

如果您得到"拒绝访问路径'd:''MyTest'。"错误,则转到解决方案资源管理器中的txt文件属性,然后将Copy to output directory属性从Do not Copy into Copy If later或Copy always