SQL Injection prevention methods

Source: Internet
Author: User
Tags sql injection prevention
// Method 1: parameterized query. Disadvantage: Increasing database pressure string connectionstring = ""; // database connection string customerid = string. empty; string companyName = string. empty; string address = string. empty; using (sqlconnection Cn = new sqlconnection (connectionstring) {CN. open (); sqlcommand cmd = new sqlcommand ("insert into MERs (customerid, companyName, address) values (@ customerid, @ companyName, @ address)", CN ); // cmd. parameters. add (New sqlparameter ("@ Cu Stomerid ", customerid); does not match the database cmd. parameters. add ("@ customerid", sqldbtype. nchar, 5, customerid); // the data type and length of this setting must be the same as that of the database Field cmd. parameters. add ("@ companyName", sqldbtype. nvarchar, 40, companyName); cmd. parameters. add ("@ address", sqldbtype. nvarchar, 60, address); cmd. executenonquery (); CN. close () ;}// Method 2: filter input information and check for any dangerous characters. Do not connect to the database /// <summary> /// check whether the input data contains dangerous characters /// </Summary> /// <Param name = "suser"> </ param> /// <Param name = "spwd"> </param> // <returns> Returns a bool value </returns> Public bool checkdata (string suser, string spwd) {If (suser. indexof ("'")! =-1 | spwd. indexof ("% ")! =-1) {return false;} return true;} // method 3: Use a stored procedure (simpleCode ) String connectionstring = ""; // database connection string customerid = string. empty; string companyName = string. empty; string address = string. empty; using (sqlconnection Cn = new sqlconnection (connectionstring) {CN. open (); string SQL = "insertuserproc"; // name of the stored procedure sqlcommand cmd = new sqlcommand (SQL, CN); cmd. commandtype = commandtype. storedprocedure; cmd. executenonquery (); CN. close ();}

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.