如何搜索数据库中是否有相同的ID?

当您尝试将数据添加到数据库时,如何检查是否存在相同的ID?

例如,如果我在列表中有名为“Leo Chan”且ID为“5”的人

当我想添加具有相同id的另一个人名,即5时,它将显示一个消息框,其中显示“列表中始终存在相同的ID”

怎么做?

using System.Data.SqlServerCe; SqlCeConnection con = new SqlCeConnection(@"Data Source=C:\Co-op\Real_ContactList\Real_ContactList\ContactDataBase.sdf;Password=**********"); 

 DataTable dt = new DataTable(); string query = string.format("SELECT * from table WHERE ID = {0}", ID); using(SqlDataAdapter sda = new SqlAdapter(query, con)) { sda.fill(dt) if(dt.Rows.count > 0) { showErrorMessage(); return; } } 

我知道有多种方法可以从数据库中读取,但我喜欢使用SqlDataAdapters,因为您实际上不必创建SqlConnection或SqlCommand。 SqlDataAdapter为您完成。