将查询包含到 C# 代码中的最佳方法
Best way to include a query into C# code
我不熟悉将数据库集成到程序中,最近我开始研究连接到 SQL 数据库的 windows 表单 (C#)。
在我的代码中,我按以下方式编写 SQL 语句:
sc.Open();
string Get_Form = ("SELECT MoM_Form.MoM_ID FROM MoM_Form WHERE MoM_Form.MoM_ID='" + TextBox_FormID.Text + "'");
SqlCommand cmd = new SqlCommand(Get_Form, sc);
int Get_Form_ID = Convert.ToInt32(cmd.ExecuteScalar());
sc.Close();
但是,我记得上过有关 SQL 注入的课程,其中明确指出您不应允许用户将数据直接插入到 SQL 语句中。
那么,这是将 SQL 语句写入代码的正确且安全的方法吗?
其次,如果我禁止用户将字符串作为 ' 插入文本框中,他是否仍然能够造成伤害?
第三,如果不是,插入它们的最佳方式是什么?使用程序和参数 ?
SO is this a correct and secure way to write SQL statements into a code?
不,不是;你的直觉是正确的。
Secondly, if i disable the user to insert strings as ' into the text box, will he still be able to do harm ?
可能吧,虽然它不会那么微不足道。
Thirdly, if it is not, which is the best way to insert them ? Using procedures and parameters ?
是的,使用参数。存储过程的使用不是必需的,尽管它们当然可以使用。您可以使用 Parameters.AddWithValue
:
将参数添加到 SqlCommand
对象
sc.Open();
string getForm = ("SELECT MoM_Form.MoM_ID FROM MoM_Form WHERE MoM_Form.MoM_ID=@id");
SqlCommand cmd = new SqlCommand(getForm, sc);
cmd.Parameters.AddWithValue("id", TextBox_FormID.Text)
int Get_Form_ID = Convert.ToInt32(cmd.ExecuteScalar());
sc.Close();
您没有使用 ORM 有充分的理由吗? Entity Framework、Linq to SQL、NHibernate,仅举几例。除非你正在做一些非常复杂的 SQL 语句,否则 ORM 每次都是合乎逻辑的选择。它将处理连接,提供一定程度的安全性(即采取措施避免 SQL 注入),并使您的代码更易于阅读和维护。
我不熟悉将数据库集成到程序中,最近我开始研究连接到 SQL 数据库的 windows 表单 (C#)。 在我的代码中,我按以下方式编写 SQL 语句:
sc.Open();
string Get_Form = ("SELECT MoM_Form.MoM_ID FROM MoM_Form WHERE MoM_Form.MoM_ID='" + TextBox_FormID.Text + "'");
SqlCommand cmd = new SqlCommand(Get_Form, sc);
int Get_Form_ID = Convert.ToInt32(cmd.ExecuteScalar());
sc.Close();
但是,我记得上过有关 SQL 注入的课程,其中明确指出您不应允许用户将数据直接插入到 SQL 语句中。
那么,这是将 SQL 语句写入代码的正确且安全的方法吗? 其次,如果我禁止用户将字符串作为 ' 插入文本框中,他是否仍然能够造成伤害? 第三,如果不是,插入它们的最佳方式是什么?使用程序和参数 ?
SO is this a correct and secure way to write SQL statements into a code?
不,不是;你的直觉是正确的。
Secondly, if i disable the user to insert strings as ' into the text box, will he still be able to do harm ?
可能吧,虽然它不会那么微不足道。
Thirdly, if it is not, which is the best way to insert them ? Using procedures and parameters ?
是的,使用参数。存储过程的使用不是必需的,尽管它们当然可以使用。您可以使用 Parameters.AddWithValue
:
SqlCommand
对象
sc.Open();
string getForm = ("SELECT MoM_Form.MoM_ID FROM MoM_Form WHERE MoM_Form.MoM_ID=@id");
SqlCommand cmd = new SqlCommand(getForm, sc);
cmd.Parameters.AddWithValue("id", TextBox_FormID.Text)
int Get_Form_ID = Convert.ToInt32(cmd.ExecuteScalar());
sc.Close();
您没有使用 ORM 有充分的理由吗? Entity Framework、Linq to SQL、NHibernate,仅举几例。除非你正在做一些非常复杂的 SQL 语句,否则 ORM 每次都是合乎逻辑的选择。它将处理连接,提供一定程度的安全性(即采取措施避免 SQL 注入),并使您的代码更易于阅读和维护。