// 前端:TextBox1(姓名) TextBox2(標題) TextBox3(內容) + Button1(送出)
protected void Button1_Click(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString;
string sql = "INSERT INTO Messages (UserName, Title, Content, PostTime) VALUES (@name, @title, @content, GETDATE())";
using (SqlConnection conn = new SqlConnection(connStr))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
// 參數化查詢:防 SQL 注入、處理特殊字元
cmd.Parameters.AddWithValue("@name", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("@title", TextBox2.Text.Trim());
cmd.Parameters.AddWithValue("@content", TextBox3.Text.Trim());
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0) LabelMsg.Text = "留言成功!";
else LabelMsg.Text = "留言失敗,請重試。";
}
}
// DAL
public class MessageRepository {
public int Add(MessageEntity m) { /* 參數化 INSERT */ }
}
// BLL
public class MessageService {
private MessageRepository _repo = new MessageRepository();
public void Post(MessageEntity m) {
if (string.IsNullOrWhiteSpace(m.Content)) throw new ArgumentException("內容不可為空");
_repo.Add(m);
}
}
// UI (Code-behind)
protected void Button1_Click(...) {
var svc = new MessageService();
try {
svc.Post(new MessageEntity { Name=txtName.Text, Title=txtTitle.Text, Content=txtContent.Text });
lblMsg.Text = "成功";
} catch (Exception ex) { lblMsg.Text = "錯誤:" + ex.Message; }
}
ASP.NET 寫入留言核心只有幾行:**參數化 SQL + using 釋放資源 + Web.config 連線字串**。切記**不要直接拼接字串**,這是新手最常犯、危害最大的錯誤。