简体   繁体   中英

Best way to include a query into C# code

I'm new to integrating databases into a program, and I've recently started working on a windows form (C#) connected to an SQL database. In my code, I'm wring the SQL statements in the following way:

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();

However, I remember taking a lesson about SQL injections, which clears out that you should not allow the user to insert data directly into an SQL statement.

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 ?

Is there a good reason you're not using an ORM? Entity Framework, Linq to SQL, NHibernate , just to name a few. Unless you're doing some pretty complex SQL statements, an ORM is the logical choice every time. It will handle the connections, provide some level of security (ie take steps to avoid SQL injection), as well as just make your code much easier to read and maintain.

SO is this a correct and secure way to write SQL statements into a code?

No it is not; your intuitions are correct.

Secondly, if i disable the user to insert strings as ' into the text box, will he still be able to do harm ?

Probably, although it won't be as trivial.

Thirdly, if it is not, which is the best way to insert them ? Using procedures and parameters ?

Yes, use parameters. The use of stored procedures is not required, although they can certainly be used. You can add a parameter to a SqlCommand object with Parameters.AddWithValue :

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM