检查 ID 是否存在(如何改进我的代码)

金箔

那么我该如何改进这段代码,这段代码有效,但我认为它看起来很难看

        cmd = con.CreateCommand()
        cmd.CommandType = CommandType.Text
        cmd.CommandText = "SELECT COUNT(*) FROM products WHERE product_id= " & prod_idbox.Text & " "
        queryResult = cmd.ExecuteScalar()

        If queryResult = 0 Then
            cmd.CommandText = "insert into products values('" + prod_idbox.Text + "','" + prodnamebox.Text + "','" + prodtypebox.Text + "', '" + pricebox.Text + "', '" + qtybox.Text + "', '" + unitbox.Text + "')"
            cmd.ExecuteNonQuery()
            MessageBox.Show("Product Inserted")
        Else
            MessageBox.Show("Product ID already Exist")
        End If
卡拉·科特里姆

您可以尝试插入该 ID,如果它在您的数据库中定义为 UNIQUE,它将引发错误,如果捕获此错误,您的 MessageBox.Show("Product ID already Exist") 将类似于:

try
 //insert
catch ( sql exception )
//print Product ID already Exist

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章