增强我的代码的指南

use*_*685 1 c# sql-server progressive-enhancement

该程序将表1中的所有记录复制到表2中,并写入文本文件.完成复制所有记录后,将删除记录,使table1为空,然后再添加新记录.我喜欢增强我的代码,例如:

  1. 喜欢插入代码来验证记录是否为空,如果在复制文件时遇到问题,或者如果是EOF,我该怎么办?
  2. 这段代码在form_load()中并在win form应用程序中运行,如果我运行程序exe,我不会出现什么形式?我想让这个程序像在Windows后面运行一样.只会出现错误或成功的消息框?
  3. 解决方案,指导或参考方面的任何帮助都非常感谢.

先感谢您!


//create connection
 SqlConnection sqlConnection1 =
   new SqlConnection("Data Source=.\SQLEXPRESS;Database=F:\Test2.mdf;Integrated Security=True;User Instance=True");
//command insert into queries
  SqlCommand cmdCopy = new SqlCommand();
  cmdCopy.CommandType = System.Data.CommandType.Text;
  cmdCopy.CommandText = "INSERT INTO tblSend (ip, msg, date) SELECT ip, msg, date FROM tblOutbox";
  cmdCopy.Connection = sqlConnection1;
//insert into text file
  SqlCommand cmd = new SqlCommand();
  cmd.CommandType = CommandType.Text;
  cmd.CommandText = "SELECT * FROM tblOutbox";
  cmd.Connection = sqlConnection1;
  sqlConnection1.Open();
  StreamWriter tw = File.AppendText("c:\INMS.txt");
  SqlDataReader reader = cmd.ExecuteReader();
  tw.WriteLine("id, ip address, message, datetime");
  while (reader.Read())
  {
   tw.Write(reader["id"].ToString());
   tw.Write(", " + reader["ip"].ToString());
   tw.Write(", " + reader["msg"].ToString());
   tw.WriteLine(", " + reader["date"].ToString());
  }
  tw.WriteLine("Report Generate at : " + DateTime.Now);
  tw.WriteLine("---------------------------------");
  tw.Close();
  reader.Close();
//command delete
  String strDel = "DELETE tblOutbox";
  SqlCommand cmdDel = new SqlCommand(strDel, sqlConnection1);
//sqlConnection1.Open(); //open con
cmdCopy.ExecuteScalar(); cmd.ExecuteNonQuery(); //execute insert query cmdDel.ExecuteScalar();//execute delete query
sqlConnection1.Close(); //close con //*****************************************************
} catch (System.Exception excep) { MessageBox.Show(excep.Message); }

Tru*_*ill 5

一些建议:

  • 将其移出表单.业务逻辑和数据访问不属于表单(View).将它移动到一个单独的类.
  • 将MessageBox代码保留在表单中.这是显示逻辑.整个try..catch可以移出方法; 只是让方法抛出异常.并且不要捕获System.Exception - 捕获您期望的数据库.
  • 我回应了Ty对IDisposable和使用语句的评论.
  • 阅读提取方法单一责任原则.这种方法做了很多,而且很长.分开来.
  • 移出一些字符串硬编码.如果连接字符串或文件路径发生变化怎么办?为什么不将它们放在配置文件中(或者至少使用一些常量)?

无论如何,对于初学者来说.:)