如何根据输入字段值动态形成SQL查询

时间:2015-05-01 15:51:15

标签: java

我有三个字段

 String stateID = "";
 String  districtID = "";
 String    talukaID = "";

这三个字段可以为空或可以有值

表的描述是

desc tbl_dealer

contactName
phone1
stateID
districtID
talukMandalID

根据重新设置的值,我必须动态编写SQL查询

根据重新设置的值,我必须动态编写SQL查询

例如

如果所有三个都为空

select contactName , phone1 from tbl_dealer 

如果stateID为空(然后从查询中删除状态)

select contactName , phone1 from tbl_dealer where districtID = "'+districtID+'" AND talukaID = "'+talukaID+'"

同样适用于所有情况

请您告诉我如何有效地解决这个问题,

1 个答案:

答案 0 :(得分:1)

您应该使用带有绑定变量的PreparedStatement来消除SQL注入的可能性(以及使DB能够缓存查询):

func applicationWillResignActive(application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

func applicationDidEnterBackground(application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

如果要在PreparedStatement ps = null; try { List<String> bindVariables = new ArrayList<>(); StringBuilder query = new StringBuilder( "select contactName, phone1 from tbl_dealer WHERE 1=1"); if (stateID.length > 0) { query.append(" AND stateID = ?"); bindVariables.add(stateID); } if (districtID.length > 0) { query.append(" AND districtID = ?"); bindVariables.add(districtID); } if (talukaID.length > 0) { query.append(" AND talukaID = ?"); bindVariables.add(talukaID); } ps = myConnection.prepareStatement(query.toString()); for (int i = 0; i < bindVariables.size(); i++) { // variables are indexed from 1 in JDBC ps.setString(i+1, bindVariables.get(i)); } ResultSet rs = ps.executeQuery(); // iterate over the result set here rs.close(); } finally { if (ps != null) { ps.close(); } } 条件下使用更多列,可以通过引入辅助方法删除代码中的一些重复。