首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

ASP.NET 留言板核心代碼:TextBox 資料寫入 SQL Server

     編輯:程式設計綜合問答

最簡單實作(教學/原型適用)

// 前端: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 = "留言失敗,請重試。";
    }
}

關鍵最佳實踐(必須養成)

  1. 參數化查詢:絕不拼接字串(`"VALUES('" + txt.Text + "')"`),防 SQL 注入、避免單引號截斷。
  2. using 區塊:自動釋放 `Connection`/`Command`,避免連線洩漏。
  3. 連線字串外置:放在 `Web.config` ``,不硬編碼。
  4. 輸入驗證:前端 `RequiredFieldValidator` + 後端 `String.IsNullOrWhiteSpace` 雙重檢查。
  5. 異常處理:`try-catch` 包裹 DB 操作,記錄日誌(`log4net`/`NLog`),友善提示用戶。

進階:三層架構雛形


// 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 連線字串**。切記**不要直接拼接字串**,這是新手最常犯、危害最大的錯誤。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved