How to give ADO.NET Parameters

前端 未结 4 1464
陌清茗
陌清茗 2020-11-30 13:38

I want to create a SQL command that adds record to DB. I tried the following code but it doesn\'t seem to be working:

SqlCommand comand = new SqlCommand(\"IN         


        
相关标签:
4条回答
  • 2020-11-30 13:55

    I think this is useful for u

    SqlCommand command = new SqlCommand("inserting", con);
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.Add("@Firstname", SqlDbType.NVarChar).Value = TextBox1.Text;
    command.Parameters.Add("@Lastname", SqlDbType.NVarChar).Value = TextBox2.Text;
    command.ExecuteNonQuery();
    
    0 讨论(0)
  • 2020-11-30 14:05

    Should use something like the following:

    SqlCommand cmd = new SqlCommand("INSERT INTO Product_table Values(@Product_Name, @Product_Price, @Product_Profit, @p)", connect);
    cmd.Parameters.Add("@Product_Name", SqlDbType.NVarChar, ProductNameSizeHere).Value = txtProductName.Text;
    cmd.Parameters.Add("@Product_Price", SqlDbType.Int).Value = txtProductPrice.Text;
    cmd.Parameters.Add("@Product_Profit", SqlDbType.Int).Value = txtProductProfit.Text;
    cmd.Parameters.Add("@p", SqlDbType.NVarChar, PSizeHere).Value = txtP.Text;
    cmd.ExecuteNonQuery();
    

    Assuming @p parameter is some NVarChar.

    Better avoid using AddWithValue, see why here: https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/

    Also at INSERT SQL statement better provide names of the values (as defined in the database) before the values themselves, as shown at https://www.w3schools.com/sql/sql_insert.asp

    0 讨论(0)
  • 2020-11-30 14:12

    In your case, it looks like you're using .NET. Using parameters is as easy as:

    C#

     string sql = "SELECT empSalary from employee where salary = @salary";
     SqlConnection connection = new SqlConnection(/* connection info */);
     SqlCommand command = new SqlCommand(sql, connection);
    
     command.Parameters.AddWithValue("salary", txtSalary.Text);
    
    0 讨论(0)
  • 2020-11-30 14:17

    Try this

    command.Parameters.AddWithValue("@parameter",yourValue);
    command.ExecuteNonQuery();
    

    I mean you forgot to use command.executeNonQuery();

    0 讨论(0)
提交回复
热议问题