该程序会将表 1 中的所有记录复制到表 2 中,并写入文本文件。完成复制所有记录后,将删除记录,使 table1 为空,然后再添加新记录。我喜欢增强我的代码,例如:
- 比如插入代码来验证记录是否为空,如果在复制文件时遇到问题,或者如果它是 EOF,我该怎么办?
- 此代码在 form_load() 中并在 win 表单应用程序中运行,如果我运行程序 exe,我不显示要出现的表单怎么办?我想让这个程序就像在后面的 Windows 上运行一样。只有错误或成功的消息框会出现?
- 在解决方案,指导或参考方面的任何帮助都非常感谢。
先感谢您!
//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);
}