Search code examples
c#sqlsql-server-2014-express

error in converting numeric values


Sql Table : stocks

Colomn Name    |  Data Type
------------------------------
Stock_no       |  nvarchar(15)
Quantity       |  int 
Gem.Weight     |  float
Cost           |  decimal(18,2)

My stock insert form code:

private void stocks_Click(object sender, EventArgs e)
{
    try
    {
        cmd = new SqlCommand("INSERT INTO Stocks VALUES('" + txt_stock_no.Text + "', '"
             + txt_qty.Text + "','" + txt_gem_weight.Text + "', '" + txt_cost.Text + "')", conn);

        MessageBox.Show("You've inserted successfully!", "Successful Message", MessageBoxButtons.OK, MessageBoxIcon.Information);                 
        conn.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

I think the the error should be with my '.text' has issues.. i tried making changing with it even though its not working.


Solution

    • Don't insert values directly from text boxes, your code is vulnerable to SQL Injection this way.

    • You have to validate the user inputs for these values from the text boxes. For example, the text box txt_stock_no should allow only integer values.

    • It would be better to list also the columns' names in the insert statement, not just the values, in case you missed or forget the order of them. and also for readability.

    • Then, Use Parameterized-Queries.

    Something like this:

    string commandText = "INSERT INTO Stocks VALUES(@stock_no, @txt_qty,@txt_gem_weight,@txt_cost)";
    
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@stock_no", SqlDbType.Int);
        command.Parameters["@stock_no"].Value = txt_stock_no.Text;
    
        ....
        // do the same for other parameters
    }
    

    Update::

    SqlCommand command = new SqlCommand(commandText, conn);
    command.Parameters.Add("@stock_no", SqlDbType.Int);
    command.Parameters["@stock_no"].Value = txt_stock_no.Text;
    
    ....
    // do the same for other parameters