C# 使用一个整数值将数据插入数据库

C# 使用一个整数值将数据插入数据库,c#,sql,C#,Sql,我正在将数据插入数据库中的表中,但一个值必须是整数。如何解决这个问题?这是我到目前为止的代码:我有3个文本框,可以将值输入其中,还有一个发送按钮 private void button1_Click(object sender, EventArgs e) { //Maak inert query string sqlIns = @"INSERT INTO Pizza (Soort, beschrijving, prijs) VALUES ('" + tex

我正在将数据插入数据库中的表中,但一个值必须是整数。如何解决这个问题?这是我到目前为止的代码:我有3个文本框,可以将值输入其中,还有一个发送按钮

private void button1_Click(object sender, EventArgs e)
{
    //Maak inert query
    string sqlIns = @"INSERT INTO Pizza (Soort, beschrijving, prijs)
            VALUES ('" + textBoxSoort.Text.Trim() + "','" + textBoxBescrhijving.Text.Trim() + "', '" + tetBoxPrijs +"') ";

    //Maak commando object
    OleDbCommand command = new OleDbCommand(sqlIns, Connectie);

    try
    {
        //Open de connectie
        Connectie.Open();

        //Voer commando uit
        command.ExecuteReader();
        Connectie.Close();

        //Opnieuw vullen DatagridVieuw
        vullendgv();
    }
    catch (OleDbException ex)
    {
        MessageBox.Show(ex.Message + ex.StackTrace, "Exception details");
    }
    finally
    {
        //Sluiten van de connectie
        Connectie.Close();
        textBoxSoort.Clear();
        textBoxBescrhijving.Clear();
        tetBoxPrijs.Clear();
    }
}

您的代码有几个问题:

  • 使用参数化查询来防止SQL注入

  • 在将输入放入查询之前验证输入。如果文本框的值应为数字,请对此进行验证或使文本框仅接受数字输入。要实现这一点,请创建一个方法,用于检查输入是否为数字(Regex或自定义代码),以及是否需要仅数字的TetxBox读取

    使用正则表达式检查输入是否为数字时的示例:

    string numericPattern = "^[0-9]+$";
    
    string input = "1zd23";
    bool result1 = Regex.IsMatch(value, numericPattern); //false
    
    string input = "456";
    bool result2 = Regex.IsMatch(value, numericPattern); //true
    
    在一种方法中:

    public bool IsNumeric(string input)
    {
        return Regex.IsMatch(input, "^[0-9]+$");
    }
    
    //Usage:
    bool result = IsNumeric("qsd4156"); //false
    
  • 在查询中,您将文本框对象
    tetBoxPrijs
    添加到查询中,而不是其值。另外,请省略单引号,否则在SQL中将不会将其视为数值。请改用此代码

    tetBoxPrijs.Text
    
    但这必须是数字,所以实际上应该是:

    Convert.ToInt32(tetBoxPrijs.Text)
    
    当然,这是没有输入验证的。可以使用提供的方法使用正则表达式进行验证:

    if(IsNumeric(tetBoxPrijs.Text))
    {
        int prijs = Convert.ToInt32(tetBoxPrijs.Text);
        //use 'prijs' in query
    }
    
更新:

更简单的是使用GarethD评论的:

int numericValue;
if(Int32.TryParse(tetBoxPrijs.Text, out numericValue))
{
    //valid, use in query
}
else
{
    //not numeric, inform the user
}

您是否收到任何异常或错误消息?你应该经常使用。这种字符串串接容易受到攻击。你应该真正使用参数,或者让自己接受sql注入。哪一个是整数?你应该使用参数来防止sql注入。@Alex我的钱在
tetBoxPrijs
:)不错的thx很有帮助,是的,我知道它对sql注入没有保护,我知道明年在学校这只是一个测试。我已经用更多的代码和解释更新了我的答案,以帮助你更进一步!:)我个人只是用它来验证。没有必要重新发明轮子。你是对的,在我写这篇文章的时候,这个轮子并没有出现在我的脑海中。我会加上的,谢谢你提醒我!:)