C#winform:为数据库访问增加价值 [英] C# winform : add value to database access

查看:64
本文介绍了C#winform:为数据库访问增加价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个代码旁边是否有任何解决方案可以实现在数据库中添加值?这比以下代码更安全。



我尝试过:



is there any solution beside this code that we can implement to add value in database ? that are more secure than this code below.

What I have tried:

OleDbCommand cmd = con.CreateCommand();    
    con.Open();    
    cmd.CommandText = "Insert into Student(FirstName,LastName)Values('" + textBox1.Text + "','" + textBox2.Text + "')";    
    cmd.Connection = con;    
    cmd.ExecuteNonQuery();    
    MessageBox.Show("Record Submitted","Congrats");    
    con.Close();   

推荐答案

是:使用参数化查询代替字符串连接:

Yes: instead of string concatenation, use parameterized queries:
OleDbCommand cmd = new OleDbCommand("Insert into Student(FirstName,LastName)Values(@FirstName,@LastName)", con);
cmd.Parameters.AddWithValue("@FirstName", textBox1.Text);
cmd.Parameters.AddWithValue("@LastName", textBox2.Text);



这样做的优点:



  • 它更容易理解:报价更少混淆,所以这里有一个语法错误更难。
  • 您的原始代码有一个 SQL注入 [ ^ ]漏洞,使用参数化查询关闭。

  • The advantages of this:


    • It's easier to read: there are less quotes to be confused about, so it's harder to have a syntax error here.
    • Your original code has an SQL injection[^] vulnerability, which is closed by using parameterized queries.

    • 不要那样做!永远不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。改为使用参数化查询。



      您还应该使用 try ... catch 来阻止您的数据库代码,并且 finally 块关闭并处理命令连接对象,或使用块自动执行此操作。
      Do not do it like that! Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.

      You should also use a try ... catch block around your DB code, and either a finally block to close and dispose the Command and Connection objects, or using blocks to do that automatically.


      首先,永远不要使用字符串连接来创建查询。某些用户输入可能会对您造成严重伤害... xkcd:对妈妈的漏洞利用 [ ^ ]

      您的代码不清楚,但如果不是,请添加用户名和密码你的连接......
      First of all NEVER use string concatenation to create you query. Certain user input can harm you very badly... xkcd: Exploits of a Mom[^]
      It is not clear from your code, but if you do not, than add username and password to your connection...


      这篇关于C#winform:为数据库访问增加价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆