Learning asp.net SQL statement query efficiency and security

Source: Internet
Author: User
Tags insert sql query trim

Take a look at this code, let's look at the main problems

The following are the referenced contents:

Set up SQL statements

insertstr= INSERT INTO UserInfo (name,password,email,phone,mobile,post,address)
VALUES (' ";
Insertstr + = This._name. Trim ()
;+ "``,``";
Insertstr + = This._password. Trim () + "', '";
Insertstr + = This._email. Trim () + "', '";
Insertstr + = This._phone. Trim () + "', '";
Insertstr + = This._mobile. Trim () + "', '";
Insertstr + = This._post. Trim () + "', '";
Insertstr + = this._address. Trim () + "')";

1. Efficiency issues

First look at the above code, the efficiency is too low, so many strings connected to their own efficiency is low enough, plus all these trim (), there is no need.

2, the correctness of the problem

This code is so fragile that a single quote can crash the entire program.

3. Safety

Ditto, using single quotes I can do a lot of things, such as running a xp_cmd command, then you are miserable, hehe.

So, how to write, the above code can be changed to this:

The following are the referenced contents:

String strSQL = "INSERT into sometable (c1, C2, C3, ...) VALUES (@c1, @c2,
@c3,...) "
SqlCommand mycommand = new SqlCommand (strSQL, myconn)
Try
{
MYCOMMAND.PARAMETERS.ADD (New SqlParameters ("@c1", Sqldatatype.varchar, 20)
mycommand.parameters["@c1"]. Value = This._name;
....
There are several plus several
....
}
catch (...)
...

In this way, the inefficient string connection can be avoided, and the SqlCommand parameter validity detection can be used to avoid the appearance of illegal characters, and because this parameter method is precompiled and more efficient.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.