데이터베이스 항목 및 양식 항목을 비교하는 방법
-
15-11-2019 - |
문제
C # 2010 Express 및 SQL Compact를 사용하고 있습니다.테이블에 저장할 데이터를 추가하는 두 열 테이블과 양식이 있습니다.그러나 나는 동일한 입장을 저장하고 싶지 않습니다.
예 :
Name City
Sefa Istanbul
Sefa New york
Sefa London
Ben New York
......
.
는 괜찮지 만 사용자가 다른 을 추가하려는 경우
Name City
Sefa Istanbul
.
또는 이미 사용 가능한 다른 항목을 사용하면 프로그램이 멈춰야합니다.
이 코드를 내 프로젝트에 추가하지만 checkcmd.executenonquery () 명령은 항상 '-1'를 반환합니다.
SqlCeConnection Baglanti = new SqlCeConnection(@"Data Source=|DataDirectory|\CeoDatabase.sdf;Password=CeoDB;Persist Security Info=True");
Baglanti.Open();
string checkcommand = "SELECT BarAdi, BarSehri FROM Barlar WHERE BarAdi = '"+ Txt_BarAdi.Text +"' AND BarSehri = '"+Txt_BarSehri.Text+"'";
SqlCeCommand checkcmd = new SqlCeCommand(checkcommand, Baglanti);
int kontrol = checkcmd.ExecuteNonQuery();
MessageBox.Show(kontrol.ToString());
return;
if (checkcmd.ExecuteNonQuery() < 1)
{
MessageBox.Show("Bu bilgiler ile kayıtlı bir bar zaten mevcut");
return;
}
else
{
SqlCeCommand Islem = new SqlCeCommand("INSERT INTO Barlar(BarAdi,BarSehri)VALUES('" + Txt_BarAdi.Text + "','" + Txt_BarSehri.Text + "')", Baglanti);
Islem.ExecuteNonQuery();
MessageBox.Show("İşlem başarıyla tamamlandı");
}
Baglanti.Close();
. 해결책
You can have it one of the ways
Either set Unique Key for that column in Database . When new record will be inserted it will be automatically checked (Preferred)
Or while Inserting new record check if that city already exist.
If you want to check for exist combination. Do somthing like this (I assume this how you have your data):
SqlCeConnection cn = new SqlCeConnection("your connection string");
string checkcommand = "SELECT [Name], [City] FROM [Tablename]" +
"WHERE [Name] == @name AND [City] == @city" ;
SqlCeCommand checkcmd= new SqlCeCommand(checkcommand, cn);
checkcmd.Parameters.AddWithValue("@name", txtBoxName.Text);
checkcmd.Parameters.AddWithValue("@city", txtBoxCity.Text);
cn.Open();
//Check if record already exist
if(checkcmd.ExecuteNonQuery() > 0)
{
//It already exist
}
else
{
//It doesn't exist Insert new record
}
제휴하지 않습니다 StackOverflow