使用参数化SQL语句进行模糊查找

今天想用参数化SQL语句进行模糊查找,一开始的使用方法不正确,摸索了好一会。

1、使用参数化SQL语句进行模糊查找的正确方法:

     //定义sql语句

      string sql = "SELECT StudentID,StudentNO,StudentName FROM Student WHERE StudentName like @StudentName";

      //给参数赋值

     command.Parameters.AddWithValue("@StudentName", "%"+txtStudentName.Text+"%");

 

2、错误做法1:

     //定义sql语句

      string sql = "SELECT StudentID,StudentNO,StudentName FROM Student WHERE StudentName like @StudentName";

      //给参数赋值

          command.Parameters.AddWithValue("@StudentName", "'%"+txtStudentName.Text+"%'");

 

3.错误做法2:

     //定义sql语句

      string sql = "SELECT StudentID,StudentNO,StudentName FROM Student WHERE StudentName like '@StudentName%'";

      //给参数赋值

     command.Parameters.AddWithValue("@StudentName", txtStudentName.Text);

 

4.错误做法3:

     //定义sql语句

      string sql = "SELECT StudentID,StudentNO,StudentName FROM Student WHERE StudentName like @StudentName%";

      //给参数赋值

     command.Parameters.AddWithValue("@StudentName", txtStudentName.Text);

 

posted @ 2012-03-17 09:43  zhouhb  阅读(11885)  评论(4编辑  收藏  举报