كيفية مقارنة إدخال قاعدة البيانات وإدخال النموذج

StackOverflow https://stackoverflow.com/questions/5053931

  •  15-11-2019
  •  | 
  •  

سؤال

أنا أستخدم C # 2010 Express و SQL Compact.لدي جدول ذو عمودين ونموذج لإضافة بيانات للحفظ إلى الجدول.لكنني لا أريد حفظ نفس الإدخال.

على سبيل المثال؛ giveacodicetagpre.

على ما يرام ولكن إذا أراد المستخدم إضافة آخر giveacodicetagpre.

أو متوفرة بالفعل إدخال آخر، يجب أن يتوقف البرنامج.

يمكنني إضافة هذا الرمز إلى مشروعي، لكن الأمر checkcmd.executenonqueryery () يعود دائما "-1" giveacodicetagpre.

هل كانت مفيدة؟

المحلول

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)enter image description here

  • 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
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top