LoginSignup
3
5

More than 3 years have passed since last update.

C#: WEBフォーム画面でSQLにデータをINSERTする

Posted at

SAMPLE

下記のWEBフォームを作成し、名前と誕生日を入力してボタンを押下するとSQLserver上のテーブルにデータをINSERTする。
image.png

SQLserver

CREATE TABLE [test_data]
    ( id INT IDENTITY(1,1)
    , name NVARCHAR(200)
    , birth DATE
    , PRIMARY KEY (id))

ASP.NET

<div>
    名前を入力してください
    <asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
    <br />
    <br />
    誕生日を入力してください
    <asp:TextBox ID="TextBoxBirth" runat="server"></asp:TextBox>
    <br />
    <br />
    <asp:Button ID="ButtonInsert" runat="server" OnClick="ButtonInsert_Click" Text="Insert" />
</div>

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {

        protected void ButtonInsert_Click(object sender, EventArgs e)
        {
            var query = String.Format("INSERT INTO [test_data] ( name, birth ) VALUES ( '{0}','{1}' )", TextBoxName.Text, TextBoxBirth.Text );


            using (SqlConnection con = new SqlConnection("Data Source=ServerName; Initial Catalog=DatabaseName; uid=UserName; pwd=Password"))
            {
                try
                {
                    // データベースの接続
                    con.Open();

                    using (var transaction = con.BeginTransaction())
                    using (var command = new SqlCommand() { Connection = con, Transaction = transaction })
                    {
                        try
                        {
                            // コマンドのセット
                            command.CommandText = query;
                            // コマンドの実行
                            command.ExecuteNonQuery();
                            // コミット
                            transaction.Commit();
                        }
                        catch
                        {
                            // ロールバック
                            transaction.Rollback();
                            throw;
                        }
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                    throw;
                }
                finally
                {
                    // データベースの接続終了
                    con.Close();
                }
            }
        }
    }
}

EXAMPLE

image.png

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5