2014-06-23 71 views
-2

我正在将数据插入到数据库中的表中,但一个值需要是整数。如何解决这个问题?这是我的代码到目前为止:我有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(); 
    } 
} 
+1

你得到任何异常或错误信息?你应该总是使用[参数化查询](http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/)。这种字符串连接对于[SQL注入](http://en.wikipedia.org/wiki/SQL_injection)攻击是开放的。 –

+0

你应该真的使用参数,或者让自己打开sql注入。 – BenR

+0

哪一个是整数? – Alex

回答

2

您对代码的几个问题:

  • 使用参数化查询防止SQL注入。 Inline queries are the devil

  • 将其放入查询之前验证输入。如果TextBox的值应该是数字,请验证该值或使TextBox仅接受数字输入。要实现这一点,请创建一个方法来检查输入是否是数字(正则表达式或自定义代码),以及是否只需要一个仅用于数字的TetxBox读取this article

    使用正则表达式来检查时的一个例子,如果输入它的数字:

    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 
    } 
    

更新:验证可以使用正则表达式所提供的方法来完成

甚至更​​简单的是使用Int32.TryParse method作为评论由GarethD:

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

好thx多数民众赞成在帮助,是的,我知道它没有保护与SQL注入,我明白学校明年在学校这只是一个测试。 – Alex3005

+0

我已经用更多的代码和解释更新了我的答案,以帮助您更进一步! :) – Abbas

+1

我个人只是使​​用['int.TryParse()'](http://msdn.microsoft.com/en-gb/library/system.int32.tryparse.aspx)进行验证。没有必要重新发明轮子。 – GarethD