SQL Server へ接続して Insert 文でテーブルにレコードを追加する(C#)
C# コードで SQL Server にあるテーブルに接続して、行を追加する例です。データベースへの接続には、SqlDataSource インスタンスを生成して接続文字列を予め設定しています。
ASPX
<asp:TextBox ID="TextBox1" runat="server" Height="216px" TextMode="MultiLine" Width="334px"></asp:TextBox><asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Article]"></asp:SqlDataSource>コードビハインド
protected void Button1_Click(object sender, EventArgs e){ // 接続文字列を指定してデータベースを指定 SqlConnection conn = new SqlConnection(this.SqlDataSource1.ConnectionString);
// 接続を開く conn.Open();
string sqlQuery = "INSERT INTO Article (Content) VALUES (@Content)"; // コマンドを作成する SqlCommand cmd = new SqlCommand(sqlQuery, conn); SqlParameter contentParam = new SqlParameter("@Content", this.TextBox1.Text); cmd.Parameters.Add(contentParam);
// コマンドを実行 cmd.ExecuteNonQuery();
// 接続を閉じる conn.Close();}
💬 コメント