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的参数
}
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();
}
}
}