💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# Jdbc Spring使用 相关jar包: jdbc spring jdbc pool(c3p0为例子) c3p0配置文件db.properties jdbc.user=root //数据库用户名 jdbc.password=root123 //数据库密码 jdbc.driverClass=com.mysql.jdbc.Driver jdbc.jdbcUrl=jdbc:mysql:///goods //连接的数据库 jdbc.initPoolSize=5 jdbc.maxPoolSize=10 spring Bean配置文件 <!-- 导入资源文件 --> <context:property-placeholder location="classpath:db.properties" /> <!-- 配置 C3P0 数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property> </bean> <!-- 配置 Spirng 的 JdbcTemplate --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> > ## JdbcTemplate jt:为上面配置的JdbcTemplate对象实例; - 更新 ``` public void testUpdate(){ String sql = "update user set u_name =? where u_id=?"; jt.update(sql,"王尼玛","3"); } - 插入 单独插入操作 ``` public void test2_1(){ String sql = "insert into user(u_name,u_jifen) values (?,?)"; int update = jt.update(sql,"妲己","233"); } ``` 批量插入操作 ``` public void test2(){ String sql = "insert into user (u_name,u_jifen) values (?,?)"; List<Object []> list = new ArrayList<Object []>(); list.add(new Object []{"刘茶几1","100"}); list.add(new Object []{"刘茶几2","100"}); list.add(new Object []{"刘茶几3","100"}); list.add(new Object []{"刘茶几4","100"}); jt.batchUpdate(sql,list); } ``` - 查询 查询多条数据 ``` //需要创建 一个RowMapper对象 。然后指定泛型。 接口 常用的实现类 。BeanPropertyRowMapper ...可以在构造器中指定, //你要把查询到的数据对应到那个类的属性当中 public void Test4(){ String sql = "select * from user"; RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class); List<User> result = jt.query(sql, rowMapper); for (User user : result) { System.out.println(user); } } public void Test6(){ String sql = "select u_name from user where u_jifen=?"; List<String> queryForList = jt.queryForList(sql, String.class,"100"); System.out.println(queryForList); } ``` 查询单独数据 ``` public void Test5(){ String sql = "select u_jifen from user where u_name=?"; Integer jifen = jt.queryForObject(sql, Integer.class, "张全蛋"); System.out.println(jifen); }