jdbc 代理 mysql_利用动态代理去实现JDBC增删改查

packagecn.dao;importjava.io.IOException;importjava.io.InputStream;import java.sql.*;importjava.util.Properties;public class JDBC_impl implementsJDBC_operation{private staticString drivate;private staticString url;private staticString username;private staticString password;privateConnection connection;privatePreparedStatement preparedStatement;privateResultSet resultSet;//静态代码块获得我们连接数据库所需要的信息

static{

Properties properties=new Properties();//这个方法可以读取配置文件.properties

InputStream in = JDBC_impl.class.getClassLoader().getResourceAsStream("database.properties");try{

properties.load(in);//load方法可以读取文件//获得配置文件里面的对应内容

drivate=properties.getProperty("jdbc.driver");

url=properties.getProperty("jdbc.connection.url");

username=properties.getProperty("jdbc.connection.username");

password=properties.getProperty("jdbc.connection.password");

}catch(IOException e) {

e.printStackTrace();

}

}//连接

@Overridepublic voidgetConnection(){try{//加载驱动

Class.forName(drivate);//获得数据库的连接

connection =DriverManager.getConnection(url, username, password);

}catch(SQLException e) {

e.printStackTrace();

}catch(ClassNotFoundException e) {

e.printStackTrace();

}

}//增删改

@Overridepublic intexecuteUpdate(String sql,Object...obj) {try{//用PreparedStatement对象去执行sql代码

preparedStatement =connection.prepareStatement(sql);//不定长参数产生的是一个数组所以我们要用for循环去遍历它的长度(不定长参数可以为空)

for (int i=0;i

preparedStatement.setObject(i+1,obj[i]);

}//执行增删改的方法

int i =preparedStatement.executeUpdate();//返回行数

returni;

}catch(SQLException e) {

e.printStackTrace();//捕获到异常则返回-1

return -1;

}

}//查询

@OverridepublicResultSet executeQuery(String sql,Object...obj) {try{//用PreparedStatement对象去执行sql代码

preparedStatement =connection.prepareStatement(sql);//不定长参数产生的是一个数组所以我们要用for循环去遍历它的长度(不定长参数可以为空)

for (int i=0;i

preparedStatement.setObject(i+1,obj[i]);

}//执行查询的方法

resultSet =preparedStatement.executeQuery();//返回结果集

returnresultSet;

}catch(SQLException e) {

e.printStackTrace();//捕获到异常则返回-1

return null;

}

}//关闭

@Overridepublic voidcloseAll() {if(resultSet!=null){try{

resultSet.close();

}catch(SQLException e) {

e.printStackTrace();

}

}if(preparedStatement!=null){try{

preparedStatement.close();

}catch(SQLException e) {

e.printStackTrace();

}

}if(connection!=null){try{

connection.close();

}catch(SQLException e) {

e.printStackTrace();

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值