如果记录存在不插入

时间:2016-04-15 19:14:19

标签: c# mysql sql asp.net database

我正在尝试一些事情,但无法弄明白。所以我正在尝试的是,如果用户在txtISN中输入内容并且它已经存在于数据库内部,则不会插入记录。我还希望在插入记录时弹出错误消息,并且插入记录时我想要弹出一条消息,说明记录已成功插入。

感谢您的帮助!

 string _connStr = @"Data Source = EJQ7FRN; Initial Catalog = BES; Integrated Security = True";
                string _query = "INSERT INTO [BES_S] (ISN,Titel,Name) values (@ISN,@Titel,@Name)";
                using (SqlConnection conn = new SqlConnection(_connStr))
                {
                    using (SqlCommand comm = new SqlCommand())
                    {
                        comm.Connection = conn;
                        comm.CommandType = CommandType.Text;
                        comm.CommandText = _query;
                        comm.Parameters.AddWithValue("@ISN", txtISN.Text);
                        comm.Parameters.AddWithValue("@Titel",txtTitel.Text);
                        comm.Parameters.AddWithValue("@Name", txtName.Text);
                        try
                        {
                            conn.Open();
                            comm.ExecuteNonQuery();
                        }
                        catch (SqlException ex)
                        {

                        }
                    }
                }

2 个答案:

答案 0 :(得分:1)

您需要稍微更改一下您的查询,但您可以使用MySql' DUAL关键字来执行此操作:

string _connStr = @"Data Source = EJQ7FRN; Initial Catalog = BES; Integrated Security = True";
string _query = "INSERT INTO [BES_S] (ISN,Titel,Name) ";
_query = _query + " SELECT @ISN, @Titel, @Name FROM DUAL";
_query = _query + " WHERE NOT EXISTS (SELECT ISN WHERE ISN=@ISN)";

using (SqlConnection conn = new SqlConnection(_connStr))
{
    using (SqlCommand comm = new SqlCommand())
    {
        comm.Connection = conn;
        comm.CommandType = CommandType.Text;
        comm.CommandText = _query;
        comm.Parameters.AddWithValue("@ISN", txtISN.Text);
        comm.Parameters.AddWithValue("@Titel",txtTitel.Text);
        comm.Parameters.AddWithValue("@Name", txtName.Text);
        try
        {
            conn.Open();
            comm.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {

        }
    }
}

DUAL就像一个虚拟表,可用于SELECT来自。{/ p>

答案 1 :(得分:0)

让数据库使用唯一约束/索引来处理这个问题:

alter table bes_s add constraint unq_bes_ISN unique (ISN);

如果插入了重复的ISN,这将导致数据库生成错误。您可以为唯一约束放置一个或多个列(如果此单个列不是唯一性的确切定义)。