我是sql初学者,
我有评论模板与按钮在它的最后添加新的注释到数据库,所以我使用SQL INSERT代码添加,它工作正常。但按钮回发后,新注释不会显示在我的标签中,直到我手动刷新页面!
我的代码在c#代码部分:
protected void Page_Load(object sender, EventArgs e)
{
ViewComments();
}
private void ViewComments()
{
hookUp =
new SqlConnection("Server=xxxx\\SQLEXPRESS;Database=WebExcerciseDB;" + "Integrated Security=True");
SqlCmd = new SqlCommand("SELECT PersonName,PersonMail,Comment FROM CommentsTable", hookUp);
try
{
hookUp.Open();
reader = SqlCmd.ExecuteReader();
while (reader.Read())
{
SQL_Result.Text += reader["PersonName"] + " " + reader["PersonMail"] + " " + reader["Comment"] +
"<br/>";
}
}
catch (Exception)
{
MessageBox.Show("Error in database code\n");
}
finally
{
reader.Close();
hookUp.Close();
}
}
protected void AddCommentBtn_Click(object sender, EventArgs e)
{
// SQL First INSRET Way //
//string InsertSQLString = "INSERT INTO CommentsTable(PersonName,PersonMail,Comment,PostDate) VALUES ('" +
// PersonName.Text + "','"+ PersonMail.Text + "','" + PersonComment.Value + "','" +
// DateTime.Now + "')";
//hookUp =
// new SqlConnection("Server=xxxx-PC\\SQLEXPRESS;Database=WebExcerciseDB;" + "Integrated Security=True");
//SqlCmd = new SqlCommand(InsertSQLString, hookUp);
//hookUp.Open();
//SqlCmd.ExecuteNonQuery();
//hookUp.Close();
// SQL First INSRET Way End //
// SQL second INSRET Way //
string InsertSQLString = "INSERT INTO CommentsTable(PersonName,PersonMail,Comment,PostDate)VALUES(@Name,@Mail,@Comment,@Date)";
hookUp =
new SqlConnection("Server=xxxx-PC\\SQLEXPRESS;Database=WebExcerciseDB;" + "Integrated Security=True");
SqlCmd = new SqlCommand(InsertSQLString, hookUp);
SqlCmd.Parameters.Add("@Name", PersonName.Text);
SqlCmd.Parameters.Add("@Mail", PersonMail.Text);
SqlCmd.Parameters.Add("@Comment", PersonComment.Value);
SqlCmd.Parameters.Add("@Date", DateTime.Now);
hookUp.Open();
SqlCmd.ExecuteNonQuery();
hookUp.Close();
// SQL second INSRET Way End //
}
}
}
谢谢你..
答案 0 :(得分:0)
这应该有所帮助:http://msdn.microsoft.com/en-us/library/ms178472.aspx#lifecycle_events