データベースエントリとフォームエントリを比較する方法
-
15-11-2019 - |
質問
C#2010 ExpressとSQL Compactを使用しています。テーブルに保存するデータを追加するための2列のテーブルとフォームがあります。しかし、私は同じエントリーを節約したくありません。
例えば;
Name City
Sefa Istanbul
Sefa New york
Sefa London
Ben New York
......
.
OKですが、ユーザーが別のを追加したい場合
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