保存,更新和删除页面。保存重复的数据

时间:2015-05-15 01:51:04

标签: c# sql

我正在观看https://www.youtube.com/watch?v=SJ-RyDl5E7U它基本上教我如何在关注视频后创建我的更新和删除按钮,我的程序就像他一样!

但是我的btnSave没有“检查”声明,允许用户在数据库中输入重复数据,如果他们点击这里多次 Duplicated data shown in the SQL database 所以我想知道是否有一个我可以使用的“检查声明”,就像IndexNumber(第一列)存在一样,会有一个消息框显示出类似“ID已经存在”的内容

这是我目前的btnSave代码

        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0; AttachDbFilename=" + Application.StartupPath + "\\GlennTeoDB.mdf; Integrated Security=True;Connect Timeout=30");
        con.Open();
        SqlCommand cmd = new SqlCommand(@"INSERT INTO GlennTeoStudents (IndexNumber,Name,Age,HandphoneNumber,GPA) VALUES ('" + numIN.Value + "','" + txtName.Text + "','" + txtAge.Text + "','" + txtHP.Text + "','" + numGPA.Value + "')", con);
        cmd.ExecuteNonQuery();
        con.Close();

2 个答案:

答案 0 :(得分:0)

您应该添加存在检查:

    SqlCommand cmd = new SqlCommand(@"INSERT INTO GlennTeoStudents (IndexNumber,Name,Age,HandphoneNumber,GPA) VALUES ('" + numIN.Value +
    "','" + txtName.Text + "','" + txtAge.Text + "','" + txtHP.Text +
    "','" + numGPA.Value + "') WHERE NOT EXISTS ( SELECT * FROM
    GlennTeoStudents WHERE IndexNumber = '" + numIN.Value + "')", con);

答案 1 :(得分:0)

当你使用像这样的ado.net时;

while (Reader.Read()) {
        if (Reader.NodeType == XmlNodeType.Element)
        {
            if (Reader.Name == "Amount")
            {
                if ("Amount" == "Gold" || value > 4999)
                {
                    credit = 300;
                    DiscountPercent = .20f;     
                }
                else if ("Amount" == "Silver" || value > 4999)
                {
                    DiscountPercent = .15f;    
                }
                else if ("Amount" == "Regular")
                {
                    credit = 200;   
                }

            }
            else if (Reader.Name == "Member")
            {
                if ("Member" == "Gold" || value > 4999)
                {
                    credit = 300;
                    DiscountPercent = .20f;
                }
                else if ("Member" == "Silver" || value > 4999)
                {
                    DiscountPercent = .15f;
                }
                else if ("Member" == "Regular")
                {
                    credit = 200;
                }

            }
        }
    }
}