public class DBAccess {
private String driver="oracle.jdbc.driver.OracleDriver";
private String url="jdbc:oracle:thin:@localhost:1521:SID";
private String user="userName";
private String pwd="passWord";
private Connection conn;
private Statement stmt;
private ResultSet rst;
public DBAccess(){
try {
Class.forName(driver);
conn=DriverManager.getConnection(url,user,pwd);
stmt=conn.createStatement();
System.out.println("连接成功");
} catch (ClassNotFoundException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (SQLException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
public ResultSet query(String sql){
try {
rst=stmt.executeQuery(sql);
} catch (SQLException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
return rst;
}
public int update(String sql){
int flag=-1;//如果返回-1说明执行失败,如果返回0成功
try {
flag=stmt.executeUpdate(sql);
} catch (SQLException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
return flag;
}
public void close(){
try{
if(rst!=null){
rst.close();
rst=null;
}
if(stmt!=null){
stmt.close();
stmt=null;
}
if(conn!=null){
conn.close();
conn=null;
}
}catch(SQLException e){
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
public Connection getConn() {
return conn;
}
public static void main(String[] args) {
DBAccess access = new DBAccess();
}
}