自己手工打造的DBUTIL包(源码1)

25 篇文章 1 订阅
21 篇文章 0 订阅



package base;


/**

*源码1和源码2都可以使用,根据自己的喜爱选择

*

*/

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;


public class BaseDao {
protected Connection conn = null;// 可用连接
// 驱动类
private static final String driver = "oracle.jdbc.driver.OracleDriver";
// 连接服务器字符串
private static final String url = "jdbc:oracle:thin:@localhost:1521:test";
// 用户名
private static final String username = "test";
// 密码
private static final String password = "123456";


protected PreparedStatement pstmt = null;



/**
* 增、删、改方法
* @throws Exception 
* @throws SQLException
*/
protected int Update(String sql,Object... params) throws Exception{

try{
getConnection();//得到连接

pstmt = conn.prepareStatement(sql);
markParams(pstmt, params);
return pstmt.executeUpdate();
}
finally{
colseAll();
}
}



/**
* 处理参数

* @param pstmt
* @param params
* @throws SQLException
*/
protected void markParams(PreparedStatement pstmt, Object... params)
throws SQLException {
if (params != null) {
int index = 1;
for (Object object : params) {
pstmt.setObject(index++, object);
}
}
}

/**
* 查询方法
* @throws SQLException
* @throws ClassNotFoundException 
*/

protected List<?> Query(String sql, Object... params) throws SQLException, ClassNotFoundException{

try{
getConnection();//得到连接

pstmt = conn.prepareStatement(sql);


//这个没有参数处理时,会出现一个丢失in,out的参数

return (List<?>) pstmt.executeQuery();
}
finally{
colseAll();
}
}


/**
* 取得连接的方法
* @throws ClassNotFoundException 
* @throws SQLException 
*/

protected Connection getConnection() throws ClassNotFoundException, SQLException {


Class.forName(driver);
conn = DriverManager.getConnection(url,username,password);

return conn;
}





/**
* 关闭所有连接的方法
* @throws SQLException
*/
protected void colseAll() throws SQLException {
// 关闭Statement
if (pstmt != null) {
pstmt.close();
}
// 关闭连接
if (conn != null) {
conn.close();
}


}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值