Using prepared statements with JDBCTemplate

前端 未结 5 899
既然无缘
既然无缘 2021-01-31 16:16

I\'m using the JDBC template and want to read from a database using prepared statements. I iterate over many lines in a .csv file, and on every line I execute some SQL select qu

5条回答
  •  春和景丽
    2021-01-31 16:50

    class Main {
        public static void main(String args[]) throws Exception {
            ApplicationContext ac = new
              ClassPathXmlApplicationContext("context.xml", Main.class);
            DataSource dataSource = (DataSource) ac.getBean("dataSource");
    // DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource");
    
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    
            String prasobhName = 
            jdbcTemplate.query(
               "select first_name from customer where last_name like ?",
                new PreparedStatementSetter() {
                  public void setValues(PreparedStatement preparedStatement) throws
                    SQLException {
                      preparedStatement.setString(1, "nair%");
                  }
                }, 
                new ResultSetExtractor() {
                  public Long extractData(ResultSet resultSet) throws SQLException,
                    DataAccessException {
                      if (resultSet.next()) {
                          return resultSet.getLong(1);
                      }
                      return null;
                  }
                }
            );
            System.out.println(machaceksName);
        }
    }
    

提交回复
热议问题