插入数据库问题 [英] Inserting into database problem

查看:53
本文介绍了插入数据库问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本框,我在其中编写以逗号(,)分隔的产品名称。我想将该产品名称插入数据库。但是如果产品名称已经存在则更新它否则

如果文本框中的新产品名称必须插入到数据库中。我该怎么做请帮助。这是我的代码。

I have an textbox in which i am writing product Names separated by a comma(,). I want to insert that product Names into database. But if the product Name already exist then update it otherwise
if a new product name in the textbox then i have to insert into database. how will i do it Please help . This is my code.

String Serials = TextBox7.Text;
    //    String[] SerialArray = Serials.Split(',');
    //    for (int i = 0; i < SerialArray.Length - 1; i++)
    //    {
    //        con.Open();
    //        string ratecard = "Insert into Ratecard (Vendor_Name,Asset_type,New,Refurbish,Repaired) values('" + TextBox1.Text + "','" + SerialArray[i] + "',0,0,0)";
    //        SqlCommand cmdd = new SqlCommand(ratecard, con);
    //        cmdd.ExecuteNonQuery();
    //        con.Close();

推荐答案

您可以按如下方式使用sp:

You can make use of sp as follows:
CREATE PROCEDURE [Insert_Update_Details]
(
   //parameters
)
AS
BEGIN
if exists (your query to check the existence of specified value) 
//update query 
else 
//insert query 
END


你可以改变sql语句位,



you can change the sql statement bit,

SqlCommand cmdd = new SqlCommand("IF NOT EXISTS(SELECT 1 from Ratecard where Vendor_Name='" + TextBox1.Text + "')" +
                " Insert INTO Ratecard (Vendor_Name,Asset_type,New,Refurbish,Repaired) VALUES('" + TextBox1.Text + "','" + SerialArray[i] + "',0,0,0)"+
                " else" +
                " UPDATE Ratecard SET Asset_type ='" + SerialArray[i] + "' WHERE  Vendor_Name= '" + TextBox1.Text + "'", con);





不要像上面那样连接sql语句,这不是最佳实践

你的程序很宽为sql注入攻击开放,尝试使用参数化的sql



Don't concatenate sql statement like above, it is not the best practice
your program is widely open for sql injection attacks, try to use parameterized sql


这篇关于插入数据库问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆