passing java string variable in mysql query

前端 未结 4 1973
时光取名叫无心
时光取名叫无心 2021-01-05 02:03

How to pass java string variable in sql query .I have done all the JDBC connection .

My sql database query is

sql = \"Select * 
       from productio         


        
4条回答
  •  悲哀的现实
    2021-01-05 02:37

    Passing variable is quiet simple in mysql query using java.

    • Write your query
    • and write the variable in ""
    • In my case i am passing 'conition' and 'tablename' dynamically.
    • Thank you very much have a good day.

      @Override public LinkedList getNameList(String condition, String tableName, String projectName) { // TODO Auto-generated method stub

      String query = "select distinct("+condition+") as name  from "+tableName+" ";
      
      //System.out.println(query);
      
      ResultSet rs = null;
      PreparedStatement preparedStatement = null;
      Connection connection = null;
      
      LinkedList finalList = new LinkedList();
      try{
          connection = dataSourceAbacus.getConnection();
          preparedStatement = connection.prepareStatement(query);
          rs= preparedStatement.executeQuery();
          while(rs.next()){
      
              finalList.add(rs.getString("name"));
          }
      }catch(Exception e){
          e.printStackTrace();
      }finally{
          if(connection !=null){
              try {
                  connection.close();
              } catch (SQLException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          }
          if(preparedStatement != null){
              try{
                  preparedStatement.close();
              }catch(Exception e){
                  e.printStackTrace();
              }
          }
          if(rs != null){
              try{
                  rs.close();
              }catch(Exception e){
                  e.printStackTrace();
              }
          }
      }
      
      return finalList;
      

      }

提交回复
热议问题