1.数据库复用模块
package cn.jzy.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBFcatory {
Connection conn ;
public DBFcatory(){
getConnection();
}
private Connection getConnection() {
conn=null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:jzy","jzy","123456");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
//增,删,改操作
public void OracleExecute(String sql,Object[] params){
try {
if(conn==null){
conn=getConnection();
}
PreparedStatement pstm=conn.prepareStatement(sql);
for(int i=0;i<params.length;i++){
pstm.setObject(i+1, params[i]);
}
pstm.execute();
closeConnection();
System.out.println("执行成功");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ResultSet OracleExecuteQuery(String sql,Object[] params){
ResultSet rs=null;
try {
if(conn==null){
conn=getConnection();
}
PreparedStatement pstm=conn.prepareStatement(sql);
for(int i=0;i<params.length;i++){
pstm.setObject(i+1, params[i]);
}
rs=pstm.executeQuery();
System.out.println("查找成功");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}
public void closeConnection(){
try {
if(conn!=null){
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
conn=null;
}
}
}
2.数据库测试模块
package cn.jzy.database;
import java.sql.ResultSet;
public class TestDBFActory {
public static void main(String[] args) {
DBFcatory dbf=new DBFcatory();
String sql="insert into emp values (seq_emp.Nextval,?,?,?,?,?,?,?,?)";
Object[] params={1,"小五",20,"女","员工","1",5000,"成都"};
dbf.OracleExecute(sql, params);
String sql2="select * from emp where id=?";
Object[] params2={1};
try{
ResultSet rs=dbf.OracleExecuteQuery(sql2, params2);
while(rs.next()){
System.out.println(rs.getString("name"));
}
dbf.closeConnection();
}catch(Exception e){
e.printStackTrace();
}
}
}