spring的jdbc

查询返回一个基本数据类型

int count = jdbcTemplate.queryForObject("sql语句",参数值,返回的值)
例如:
int count = jdbcTemplate.queryForObject(
                "select count(*) from all_word_and_wordbook where name=?",new String[]{"四级"},Integer.class);

查询返回单个对象

Word word = jdbcTemplate.queryForObject("select * from word limit 0,1", new RowMapper<Word>() {
            @Override
            public Word mapRow(ResultSet resultSet, int i) throws SQLException {
                return new Word(resultSet.getInt(1),
                        resultSet.getString(2),
                        resultSet.getString(3),
                        resultSet.getString(4),
                        resultSet.getInt(5));
            }
        });

查询返回链表

List<Word> words = jdbcTemplate.query("select * from word limit ?,?",new Integer[]{1,5}, new RowMapper<Word>() {
            @Override
            public Word mapRow(ResultSet resultSet, int i) throws SQLException {
                return new Word(resultSet.getInt(1),
                        resultSet.getString(2),
                        resultSet.getString(3),
                        resultSet.getString(4),
                        resultSet.getInt(5));
            }
        });

可以将RowMapper提取出来,重复使用

 @Test
    public void testQueryForObject(){
        List<Word> words = jdbcTemplate.query("select * from word limit ?,?",new Integer[]{1,5}, new WordMapper());
        System.out.println(words);
    }

    public static class WordMapper implements RowMapper<Word>{
        @Override
        public Word mapRow(ResultSet resultSet, int i) throws SQLException {
            return new Word(resultSet.getInt(1),
                    resultSet.getString(2),
                    resultSet.getString(3),
                    resultSet.getString(4),
                    resultSet.getInt(5));
        }
    }

插入数据

jdbcTemplate.update(
                "insert into word(wordEnglishText,wordChineseText,phonetic_symbols,proficiency) " +
                        "values(?,?,?,?)","generic","通用的","",0);

更新数据

jdbcTemplate.update(
                "update word set proficiency = 2 where id = ? ",6330);

删除数据

 jdbcTemplate.update(
                "delete from word where id = ? ",6330);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容