如何在JAVA中将语句转换为PreparedStatement

时间:2016-06-03 16:27:56

标签: java sql jdbc prepared-statement

我喜欢将旧的更改为新的和我的旧sql查询其语句,我想更改为准备好的语句。我怎么能改变? 例如:

*

strSql = "SELECT Id as GroupId, Name,Description FROM Groupcodes WHERE deleteFlag=0 and GroupType = '" + StrGroupType +  "' ";
 if(strSearchBy.length() > 0 && strSearchText.length() > 0)
      {
          if(strSearchOption.equalsIgnoreCase("Starts With")) {
              strSql += " AND " + strSearchBy + " LIKE '" + strSearchText + "%' ";
          }
          else if(strSearchOption.equalsIgnoreCase("Contains")){
              strSql += " AND " + strSearchBy + " LIKE '%" + strSearchText + "%'" ;
          } 
      }   

      strSql += " ORDER BY Name ASC";

      if( nCounter > 0 )  {   
          strSql += " LIMIT " + (nCounter - 1) + ", " + nMaxCount;
      }

*

一旦你教导这个例子,那么我将为即将到来的代码做。

1 个答案:

答案 0 :(得分:0)

你这样做:

PreparedStatement mStatement = getDBTransaction().createPreparedStatement("select * from test_table where user_id = ?", 0);
    mStatement.setString(1, "4913");
    ResultSet rs = mStatement.executeQuery();

'?'字符对查询进行参数化,然后使用setString设置其值。请注意,在setstring函数中,第一个参数由索引1(不是0)表示。另请注意,如果您的条件是比较varchars

,则不需要''
相关问题