我想像这样使用变量作为运算符;
DECLARE @OP VARCHAR(3) = 'AND' -- THIS COULD BE 'AND','OR'
SELECT * FROM tblName WHERE Col1 = 1 @OP Col2 = 3
很明显,我不能使用VARCHAR,我唯一想到的就是SQL注入,但是我想知道是否有一个更简单的解决方案。
请帮忙。
答案 0 :(得分:2)
您可以尝试执行动态SQL,但是即使没有动态SQL,我们也可以执行此操作:
public class AllUserListFragment extends Fragment{
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference allUsers = db.collection("users");
private AllUserAdapter mUserAdapter;
public AllUserListFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_all_user_list, container, false);
Query query = allUsers;
FirestoreRecyclerOptions<AllUsers> recyclerOptions = new FirestoreRecyclerOptions.Builder<AllUsers>()
.setQuery(query, AllUsers.class)
.build();
mUserAdapter = new AllUserAdapter(recyclerOptions);
RecyclerView recyclerView = view.findViewById(R.id.allUser_listView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(mUserAdapter);
mUserAdapter.setOnItemClickListener(new AllUserAdapter.OnItemClicklistener() {
@Override
public void onItemClick(DocumentSnapshot snapshot, int position) {
AllUsers allUsers = snapshot.toObject(AllUsers.class);
String id = snapshot.getId();
Bundle bundle = new Bundle();
bundle.putString("visit_user_id", id);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
AllUserProfileFragment fragment = new AllUserProfileFragment();
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.frameLayout, fragment);
fragmentTransaction.commit();
}
});
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@Override
public void onStart() {
super.onStart();
mUserAdapter.startListening();
}
答案 1 :(得分:1)
为完成此任务,动态SQL解决方案将是:
DECLARE @Op nvarchar(3) = N'AND';
DECLARE @SQL nvarchar(MAX);
SET @SQL = N'SELECT * FROM TblName WHERE Col1 = 1 ' + CASE WHEN @OP IN (N'AND',N'OR') THEN @OP END + N' Col2 = 3;';
EXEC sp_executesql @SQL;
CASE
可以避免注入,因为@Op
的值必须为AND
或OR
(否则将产生@SQL
的值NULL
中的任何内容都不会运行)。
如果您需要参数化Col1
和Col2
的值,那么它将是:
DECLARE @OP nvarchar(3) = N'AND';
DECLARE @SQL nvarchar(MAX);
DECLARE @col1 int = 1, @col2 int =3;
SET @SQL = N'SELECT * FROM TblName WHERE Col1 = @dCol1 ' + CASE WHEN @OP IN (N'AND',N'OR') THEN @OP END + N' Col2 = @dCol2;';
EXEC sp_executesql @SQL,N'@dCol1 int, @dCol2 int', @dCol1 = @Col1, @dCol2 = @Col2;