C#
(C#) 데이터베이스에 SQL update 구문을 실행하는 코드
코딩ABC
2023. 4. 19. 08:15
반응형
SQL Server 또는 LocalDB에 C#으로 데이터베이스의 데이터를 갱신(update)하는 코드입니다.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
...
string connectionString =
@"Server=(LocalDB)\MSSQLLocalDb;database=haksa;integrated security=true";
...
private void btnUpdate_Click(object sender, EventArgs e)
{
// 데이터베이스 student 테이블에 update
if (txtHakbun.Text.Trim().Length != 7)
{
MessageBox.Show("학번은 7자리입니다.");
txtHakbun.Focus();
return;
}
if (txtName.Text.Trim() == "")
{
MessageBox.Show("이름을 입력하세요.");
txtName.Focus();
return;
}
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connectionString;
conn.Open();
string sql = "update student set name=@name, sx=@sx, deptCD=@deptCD " +
"where hakbun=@hakbun";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@name", txtName.Text.Trim());
string sx = "0";
if (rdM.Checked) sx = "1";
else if (rdW.Checked) sx = "2";
cmd.Parameters.AddWithValue("@sx", sx);
cmd.Parameters.AddWithValue("@deptCD", "00");
cmd.Parameters.AddWithValue("@hakbun", txtHakbun.Text.Trim());
try
{
int n = cmd.ExecuteNonQuery();
MessageBox.Show(n + "건이 update 되었습니다.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
update를 실행하기 이전의 화면
update를 실행한 후 화면
반응형