このプログラムは、テーブル 1 内のすべてのレコードをテーブル 2 にコピーし、テキスト ファイルにも書き込みます。すべてのレコードのコピーが完了すると、新しいレコードが追加される前に、レコードが削除され、table1 が空になります。たとえば、コードを強化したい:
- レコードが空かどうかを確認するコードを挿入したり、ファイルのコピーで問題が発生した場合、または EOF の場合はどうすればよいですか??
- このコードは form_load() 内にあり、win フォーム アプリケーションで実行されていました。プログラム exe を実行すると、フォームが表示されない場合はどうなりますか? このプログラムを背後のウィンドウで実行されているようにしたい。エラーまたは成功のメッセージボックスのみが表示されますか?
- 解決策、ガイダンス、またはリファレンスのヘルプは非常に感謝しています。
前もって感謝します!
//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);
}