C#
ACCESS를 사용한 DB연결 -2
hyun0229
2022. 5. 11. 10:44

이어서 추가버튼을 추가
private void btnAdd_Click(object sender, EventArgs e)
{
if (txtSId.Text == "" || txtSName.Text == "" || txtPhone.Text == "")
return;
connOpen();
// sql 문장 만들기
string sql = string.Format(
"INSERT INTO StudentTable(SId,SName,Phone) VALUES({0},'{1}','{2}')",
txtSId.Text, txtSName.Text, txtPhone.Text);
//MessageBox.Show(sql);
comm = new OleDbCommand(sql, conn);
int x = comm.ExecuteNonQuery();
if (x == 1)
MessageBox.Show("삽입 성공!"); //실행성공
connClose();
}
위에 보이는 int x는 DB에 삽이이 성공했을 경우 1을 반환하기 때문에 실행 성공시 메세지 박스를 출력하게 만들었다.
coonOpen();과 connClose();는 아래와 같다
private void connClose()
{
conn.Close();
conn = null;
lstStudent.Items.Clear();
DisplayStudents();
}
private void connOpen()
{
// DB연결
conn = new OleDbConnection(connStr);
conn.Open();
}
각각 DB를 연결하고 중지하는 역할을 한다.
이어서 삭제버튼
private void btnDelete_Click(object sender, EventArgs e)
{
if (txtID.Text == "")
return;
connOpen();
string sql = string.Format(
"DELETE FROM StudentTable WHERE ID={0}",
txtID.Text);
comm = new OleDbCommand(sql, conn);
int x = comm.ExecuteNonQuery();
if (x == 1)
MessageBox.Show("삭제 성공!");
connClose();
}
위의 삭제 버튼은 처음에 txtID가 이름인 텍스트 박스에 값이 들어가있지 않으면 실행되지 않는다.
txtID에 값이 존재한다면 그 번호의 찾아 삭제한다.
int x는 위의 추가 버튼과 같다.
검색버튼과 수정 버튼은 다음에 이어서 하겠다.