java [30] JDBCTemplate配合DBCP连接池使用

只需要传入sql语句和参数即可,不需要获取连接和关闭连接。

package com.us.spring;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
/*
 * 
 * dbcp实现了database 接口对数据源进行了封装
 * JdbcTemplate 类实现了*/
import com.us.sqltable.userInfo;

import datasource.DBCPUtils;

public class JdbcTemnpleteTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
	/*	userInfo user = findUser1("ok");
		System.out.println("user " + user);
		List users = findUsers(4);
		System.out.println(users);
		int i = getUsrCount();
		System.out.println("count:" + i);*/
		Map map = getData(1);
		System.out.println(map);
		System.out.println(map.get("username"));
	}
	
	//获取主键
	static int addUser(userInfo user) {
		JdbcTemplate jdbc = new JdbcTemplate( );
		jdbc.setDataSource((DataSource)DBCPUtils.getDataSource());
		jdbc.execute(new ConnectionCallback() {

			@Override
			public Object doInConnection(Connection con) throws SQLException, DataAccessException {
				String sql = "insert into userInfo(username,passwd,type,birthday,money) values (?,?,?,?,?)";
				PreparedStatement ps = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
				ps = con.prepareStatement(sql);
				ps.setString(1, user.getUsername());
				ps.setString(2, user.getPasswd());
				ps.setString(3, user.getType());
				ps.setDate(4, new Date(user.getBirthday().getTime()));
				ps.setFloat(5, user.getMoney());
				ps.executeUpdate();
				ResultSet rs = ps.getGeneratedKeys();
				if (rs.next()) {
					user.setId(rs.getInt(1));
				}
				return null;
			}
		});
		
		
		
		return user.getId();
	}
	
	static Map getData(int id){
		JdbcTemplate jdbc = new JdbcTemplate( );
		jdbc.setDataSource((DataSource)DBCPUtils.getDataSource());
		String sql = "select username,passwd as password,type from userInfo where id = " + id;
		return jdbc.queryForMap(sql);
		
	}
	
	static String getUsrName(int id) {
		JdbcTemplate jdbc = new JdbcTemplate( );
		jdbc.setDataSource((DataSource)DBCPUtils.getDataSource());
		String sql = "select name from userInfo where id = " + id;
		String name = jdbc.queryForObject(sql, String.class);
		return name;
	}
	
	@SuppressWarnings("deprecation")
	static int getUsrCount() {
		JdbcTemplate jdbc = new JdbcTemplate( );
		jdbc.setDataSource((DataSource)DBCPUtils.getDataSource());
		String sql = "select count(*) from userInfo";
		return jdbc.queryForInt(sql);
	}
	
	//获取列表多条记录
	static List  findUsers(int id) {
		//jdbc可添加数据源
		JdbcTemplate jdbc = new JdbcTemplate( );
		jdbc.setDataSource((DataSource)DBCPUtils.getDataSource());
		String sql = "select username,passwd,type,birthday,money from userInfo where id<?";
		//假如数据库中的名字跟java类中的名字对应不起来,可以使用别名同样实现
		//String sql = "select user_name,passwd,type,birthday,money from userInfo where username=?";
		Object[] args = new Object[] {id};
		//userInfo user=new userInfo();
		List users = jdbc.query(sql, args, new BeanPropertyRowMapper(userInfo.class));
		return users;
	}
	//查询一条记录 如果是多条会报错
	static userInfo findUser1(String name) {
		//jdbc可添加数据源
		JdbcTemplate jdbc = new JdbcTemplate( );
		jdbc.setDataSource((DataSource)DBCPUtils.getDataSource());
		String sql = "select username,passwd,type,birthday,money from userInfo where username=?";
		//假如数据库中的名字跟java类中的名字对应不起来,可以使用别名同样实现
		//String sql = "select user_name,passwd,type,birthday,money from userInfo where username=?";
		Object[] args = new Object[] {name};
		//userInfo user=new userInfo();
		Object user = jdbc.queryForObject(sql, args, new BeanPropertyRowMapper<userInfo>(userInfo.class));
		return (userInfo)user;
	}
	static userInfo findUser(String name) {
		//jdbc可添加数据源
		JdbcTemplate jdbc = new JdbcTemplate( );
		jdbc.setDataSource((DataSource)DBCPUtils.getDataSource());
		String sql = "select username,passwd,type,birthday,money from userInfo where username=?";
		Object[] args = new Object[] {name};
		userInfo user=new userInfo();
		jdbc.queryForObject(sql, args, new RowMapper<Object>() {

			@Override
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				user.setUsername(rs.getString("username"));
				user.setPasswd(rs.getString("passwd"));
				user.setType(rs.getString("type"));
				user.setBirthday(rs.getDate("birthday"));
				user.setMoney(rs.getFloat("money"));
				return user;
			}
		});
		return (userInfo)user;
	}

}

方式一:Object user = jdbc.queryForObject(sql, args, new BeanPropertyRowMapper<userInfo>(userInfo.class));能够直接返回对象,自己内部完成,不需要对对象进行操作。

方式二:jdbc.queryForObject(sql, args, new RowMapper<Object>()需要对rowmapper进行重写。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 SSM 整合中,可以使用 Spring 的 JdbcTemplate 或 MyBatis 框架来操作数据库。连接的设置与具体使用的数据库连接有关。 如果使用的是 Spring 的 JdbcTemplate,可以通过配置数据源(DataSource)来实现连接的设置。配置数据源时,可以指定连接的类型、最大连接数、最小连接数、空闲连接的最大存活时间等参数。常用的连接有 Apache Commons DBCP、C3P0、HikariCP 等,可以根据自己的需求选择合适的连接。 如果使用的是 MyBatis 框架,可以在配置文件中设置连接相关的参数。MyBatis 默认使用的是 Apache Commons DBCP 连接,可以通过在配置文件中设置属性来修改连接的参数。例如: ```xml <dataSource type="POOLED"> <property name="driver" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="poolMaximumActiveConnections" value="50"/> <property name="poolMaximumIdleConnections" value="10"/> <property name="poolMaximumCheckoutTime" value="20000"/> <property name="poolPingEnabled" value="true"/> <property name="poolPingQuery" value="SELECT 1"/> </dataSource> ``` 上述代码中,`type` 属性指定了使用连接类型为 POOLED,`poolMaximumActiveConnections` 属性指定了连接中最大的活跃连接数为 50,`poolMaximumIdleConnections` 属性指定了连接中最大的空闲连接数为 10,`poolMaximumCheckoutTime` 属性指定了连接连接的最大存活时间为 20000 毫秒,`poolPingEnabled` 属性指定了是否开启连接的心跳检测,`poolPingQuery` 属性指定了心跳检测的 SQL 查询语句为 SELECT 1。 总之,连接的设置与具体的框架和连接有关,需要根据实际情况选择合适的连接,并在配置文件中设置连接相关的参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值