passing java string variable in mysql query

前端 未结 4 2008
时光取名叫无心
时光取名叫无心 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:27

    Use a PreparedStatement and bind the String parameter,

    final String sql = "select * from production AS cust INNER JOIN location"
        + " AS comp ON cust.location_id = comp.location_id where "
        + "comp.name = ? AND crop_id = 1";
    PreparedStatement ps = null;
    try {
      ps = conn.prepareStatement(sql);
      ps.setString(1, "taplejung");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (ps != null) {
        try {
          ps.close();
        } catch (Exception ignored) {
        }
      }
    }
    

    Edit (Based on your additional code, change it to something like)

    PreparedStatement ps = null;
    
    String sql = null;
    if (cropnames.equals("paddy")) {
      // System.out.println();
      sql = "SELECT * FROM `production` AS cust INNER JOIN location AS comp "
          + "ON cust.location_id = comp.location_id WHERE comp.name = "
          + "? AND crop_id = 1";
    } else {
      sql = "SELECT * FROM `production` WHERE crop_id = 4 AND location_id = 10";
    }
    ps = conn.prepareStatement(sql);
    if (cropnames.equals("paddy")) {
      ps.setString(1, locationnames);
    }
    System.out.println(sql);
    ResultSet rs = ps.executeQuery();
    

提交回复
热议问题