//数据库连接地址
private static final String URL="jdbc:oracle:thin:@127.0.0.1:1521:orcl";
//数据库驱动类的地址
private static final String DRIVER="oracle.jdbc.driver.OracleDriver";
//数据库连接登录用户名
private static final String UNAME="system";
//数据库连接登录密码
private static final String UPWD="Szk12345";
//静态块:当类加载的时候首先执行该区域
//加载数据库驱动
static{
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected Connection conn = null;//数据库连接对象
protected ResultSet res = null;//数据库查询后结果集对象
protected PreparedStatement pstmt= null;//SQL语句预处理对象
//数据库连接的方法
//取得连接使用工厂设计模式
//取得连接语法
Class.forName
DriverManager.getConnection
//必须关闭
private void getConn(){
try {
conn = DriverManager.getConnection(URL, UNAME, UPWD);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 数据库关闭的方法
*/
public void closeAll(){
if(null!=res){
try {
res.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(null!=pstmt){
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(null!=conn){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 查询数据库中的数据
* @param sql
* @param params
* @return
*/
protected ResultSet excuteFind(String sql,Object[] params){
//调用数据库连接的方法
this.getConn();
//创建数据库预处理对象
try {
pstmt = conn.prepareStatement(sql);
if(null!=params){
for (int i = 0; i < params.length; i++) {
//将参数处理到sql语句中
pstmt.setObject(i+1, params[i]);
}
}
res = pstmt.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
/**
* 执行数据库增,删,改的功能
* @param sql
* @param params
* @return
*/
protected int excuteUpdate(String sql,Object[] params){
//返回操作后的影响的行数
int count = 0;
this.getConn();
try {
pstmt = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pstmt.setObject(i+1, params[i]);
}
count = pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
this.closeAll();
}
return count;
}
ResultSet:当接受到数据时,处于第0行(字段行)
while(re.next){
int id = rs.getInt("id");
String name = rs.getString("name");
double salary = rs.getDouble("salary");
Date date = rs.getDate("date");
}
相同的含义:
下标从1开始
while(re.next){
int id = rs.getInt(1);
String name = rs.getString(2);
double salary = rs.getDouble(3);
Date date = rs.getDate(4);
}