数值转换错误

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)

我的股票插入表格代码:

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);
    }
}

我认为错误应该是我的“.text”有问题。我尝试用它进行更改,即使它不起作用。

将您的代码替换为:

cmd = new SqlCommand("INSERT INTO Stocks VALUES('" + txt_stock_no.Text + "', "+ txt_qty.Text + "," + txt_gem_weight.Text + "," + txt_cost.Text + ")", conn);
int rowseffected=cmd.ExecuteNonQuery();
//rest of your code goes here...

However, this is not recommended. This is query is vulnerable to SQL injection. Use parameters instead, you will not face issue like this again.

  • 不要直接从文本框中插入值,这样您的代码很容易受到 SQL Injection 的攻击。

  • 您必须验证用户从文本框中输入的这些值。例如,文本框 txt_stock_no 应该只允许整数值。

  • 最好在插入语句中也列出列的名称,而不仅仅是值,以防您错过或忘记它们的顺序。以及可读性。

  • 然后,使用Parameterized-Queries.

像这样:

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
}

更新:

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