标签:
相关知识:
string strCmd = "SELECT AccountID FROM Account WHERE AccountName=@AccountName AND password=@password";
对于SQL Server数据库,“@”是参数的前缀。上句中定义了两个参数:@AccountName,@password。
SqlCommand cmd = new SqlCommand(strCmd, conn); cmd.Parameters.AddWithValue("@AccountName", userName); cmd.Parameters.AddWithValue("@password", password); cmd.ExecuteReader();
代码示例:
1 static void Main(string[] args) 2 { 3 string userName = "Joe"; 4 string password = "123456"; 5 6 string strConn = @"server=Joe-PC;database=AccountDBforSQLInjection;uid=sa;pwd=root"; 7 SqlConnection conn = new SqlConnection(strConn); 8 9 string strCmd = "SELECT AccountID FROM Account WHERE AccountName=@AccountName AND password=@password"; 10 SqlCommand cmd = new SqlCommand(strCmd, conn); 11 12 cmd.Parameters.AddWithValue("@AccountName", userName); 13 cmd.Parameters.AddWithValue("@password", password); 14 15 try 16 { 17 conn.Open(); 18 SqlDataReader dr = cmd.ExecuteReader(); 19 if (dr.Read()) 20 { 21 Console.WriteLine("成功"); 22 } 23 else 24 { 25 Console.WriteLine("失败"); 26 } 27 } 28 catch (Exception e) 29 { 30 Console.WriteLine(e); 31 } 32 finally 33 { 34 conn.Close(); 35 } 36 }
标签:
原文地址:http://www.cnblogs.com/chenguangqiao/p/4353845.html