使用 sql 语句在插入之前检查该行。这是一个名为 person 的表的简单示例,该表有两列,名字和姓氏,它们被检查唯一性:
/// <summary>
/// Insert a row into the person table
/// </summary>
/// <param name="connection">An open sql connection</param>
/// <param name="forename">The forename which will be inserted</param>
/// <param name="surname">The surname which will be inserted</param>
/// <returns>True if a new row was added, False otherwise</returns>
public static bool InsertPerson(SqlConnection connection, string forename, string surname)
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText =
@"Insert into person (forename, surname)
Select @forename, @surname
Where not exists
(
select 'X'
from person
where
forename = @forename
and surname=@surname
)";
command.Parameters.AddWithValue("@forename", forename);
command.Parameters.AddWithValue("@surname", surname);
int rowsInserted = command.ExecuteNonQuery();
// rowsInserted will be 0 if the row is already in the database
return rowsInserted == 1;
}
}