usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Data.SqlClient;namespace_01 parameterized login to prevent SQL injection attacks { Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); } Private voidBtnlogin_click (Objectsender, EventArgs e) { Objectobj; //Get your account and password//preparing the connection string stringstr ="Data source=xy-pc;initial catalog=myitcast;integrated security=true"; using(SqlConnection con=NewSqlConnection (str)) { //String sql =string. Format ("Select COUNT (*) from userlogin where Username= ' {0} ' and userpwd= ' {1} '", Txtname.text,txtpwd.text);//this can be exploited by SQL injection . stringsql ="Select COUNT (*) from userlogin where [email protected] and [email protected]"; //not all of the values are to be replaced in a parameterized way, and when are parameters used without parameters? //the user input is the parameter using(SqlCommand cmd=NewSqlCommand (Sql,con)) {con. Open (); Cmd. Parameters.addwithvalue ("@name", txtName.Text); Cmd. Parameters.addwithvalue ("@pwd", Txtpwd.text); Obj=cmd. ExecuteScalar (); } } if(Convert.ToInt32 (obj) >0) {MessageBox.Show ("Login Successful"); } Else{MessageBox.Show ("Logon Failure"); } //connecting to a database } }}
parameterized login to prevent SQL injection attacks