最近在写一个程序,用户界面有多个查询条件,如果条件不输则不加入条件,因考虑注入安全问题,不能直接拼接字符串,必须参数化查询,网上也没有找到关于这方面的案例,自己最后想了一下,用最简单原始的方法拼接语句再判断条件添加Parameters实现了功能。
Dim SqlText As String = "SELECT [EMP_ID],[EMP_NAME],[BM_NAME] FROM [BASIC_YGZL] WHERE 1=1"
If String.IsNullOrEmpty(TextBox_empid.Text) = False Then SqlText = SqlText & " AND EMP_ID = @EMP_ID" End If da = New SqlDataAdapter(SqlText, cn) da.SelectCommand.CommandType = CommandType.Text If String.IsNullOrEmpty(TextBox_empid.Text) = False Then SqlText = SqlText & " AND EMP_ID = @EMP_ID" end if