public class LsDataSourceUtils {
public class LsDataSourceUtils {
// 获取Druid数据库连接池对象
private static DataSource dataSource;
/**
* 使用静态代码块 读取配置文件内容 加载 Druid数据库连接池
*/
static {
try {
// 读取src目录下 druid.properties
Properties properties=new Properties();
InputStream resourceAsStream = LsDataSourceUtils.class.getClassLoader().getResourceAsStream("druid.properties");
properties.load(resourceAsStream);
// 交给我们的Druid数据库连接池
dataSource = DruidDataSourceFactory.createDataSource(properties);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 封装获取连接的方法
*/
public static Connection getConnection(){
try {
return dataSource.getConnection();
}catch (Exception e){
return null;
}
}
/**
* 释放jdbc连接
*/
public static void close(Connection connection, Statement statement, ResultSet resultSet){
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
public static void close(Connection connection, Statement statement){
close(connection,statement,null);
}
public class Test {
public static void main(String[] args) throws SQLException {
Connection connection=LsDataSourceUtils.getConnection();
// 获取预编译执行者对象 防止sql注入的问题
PreparedStatement preparedStatement=
connection.prepareStatement("select *from user where id=? ");
//设置参数
preparedStatement.setLong(1,2);
//执行sql
ResultSet resultSet=preparedStatement.executeQuery();
if(!resultSet.next()){
return;
}
// 对结果进行处理
// 获取该行数据第一列的id
long id = resultSet.getLong("id");
// 获取该行数据第二列的name
String name = resultSet.getString("name");
// 获取该行数据第三列的age
int age = resultSet.getInt("age");
// 将db中查询到数据封装成user对象
UserEntity userEntity=new UserEntity(id,name,age);
System.out.println(userEntity);
}
}