转换数值时出错

问题描述 投票:0回答:2
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'有问题..我试着改变它,即使它不起作用。

c# sql sql-server-2014-express
2个回答
1
投票
  • 不要直接从文本框插入值,您的代码很容易受到这种方式的SQL Injection攻击。
  • 您必须从文本框中验证这些值的用户输入。例如,文本框txt_stock_no应该只允许整数值。
  • 最好在insert语句中列出列的名称,而不仅仅是值,以防错过或忘记它们的顺序。并且还为了可读性。
  • 然后,使用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

-2
投票

用以下代码替换您的代码:

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...

但是,不建议这样做。这是查询易受SQL注入攻击。使用参数代替,您将不会再遇到这样的问题。

© www.soinside.com 2019 - 2024. All rights reserved.