gpt4 book ai didi

c# - 增强我的代码的指南

转载 作者:太空宇宙 更新时间:2023-11-03 17:23:14 25 4
gpt4 key购买 nike

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

  1. 比如插入代码来验证记录是否为空,如果在复制文件时遇到问题,或者如果是 EOF,我该怎么办??
  2. 此代码在 form_load() 中并在 win 窗体应用程序中运行,如果我运行程序 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<br/>
cmdCopy.ExecuteScalar();
cmd.ExecuteNonQuery(); //execute insert query
cmdDel.ExecuteScalar();//execute delete query<br/>
sqlConnection1.Close(); //close con
//*****************************************************<br/>
}
catch (System.Exception excep)
{
MessageBox.Show(excep.Message);
}

最佳答案

一些建议:

  • 将其移出表单。业务逻辑和数据访问不属于表单(View)。将其移至单独的类(class)。
  • 将 MessageBox 代码保留在表单中。这就是显示逻辑。整个try..catch可以移出方法;只是让方法抛出异常。并且不要捕获 System.Exception - 捕获您期望的数据库异常。
  • 我赞同 Ty 关于 IDisposable 和 using 语句的评论。
  • 继续阅读 Extract MethodSingle Responsibility Principle .这个方法做了很多,而且很长。打破它。
  • 移出一些字符串硬编码。如果您的连接字符串或文件路径发生变化怎么办?为什么不将它们放在配置文件中(或至少使用一些常量)?

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

关于c# - 增强我的代码的指南,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1376996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com