c# - MySQL 如果不存在则插入/忽略

标签 c# mysql insert exists

基本上这是我的表格布局:

Type_Of     Agreement
iPad        Heyo! I'm an agreement!
iPod Touch  I'm another agreement!

基本上,我正在构建一个管理界面,管理员可以在其中添加新类型。我希望它能够使他/她无法输入已经存在的新类型。基本上,在上面的示例中,如果他们在新类型框中输入“iPad”并按提交,它将被忽略或抛出错误或其他内容。

这是我现有的 MySQL 语句:

INSERT IGNORE INTO agreements (Type_Of, Agreement) VALUES (?, ?)
com.Parameters.AddWithValue("", Request.Form["pies"]);
com.Parameters.AddWithValue("", "Wahey! A sample license!");

最佳答案

(升级到答案)

您需要在 Type_Of 上定义一个 UNIQUE 索引。如 the manual 中所述:

A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL. If you specify a prefix value for a column in a UNIQUE index, the column values must be unique within the prefix.

因此:

ALTER TABLE agreements ADD UNIQUE INDEX (Type_Of);

关于c# - MySQL 如果不存在则插入/忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10901841/

相关文章:

c# - 如何在IdentityServer4/Identity中配置角色声明名称

c# - 将变量传递给 .NET 中的事件

php - Codeigniter 中的安全类

mysql - 在 MySQL 中使用 CI 排序规则区分大小写

C 列表插入程序 - 运行时出现段错误

mysql - 根据现有列值插入新列

c# - 如何将 IQueryable<T> 转换为 ObjectQuery<T>?

c# - 有什么方法可以缩短具有大量字段的查询吗?

php - sql查询的最佳字符集编码是什么?

hadoop - hive >插入覆盖表/本地目录不起作用