import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 数据库访问公共类
* @author wen
* @version 1.0
* @since 1.5
*/
public class DBAccess {
private String CLASSPATH = "oracle.jdbc.driver.OracleDriver";
private String URL = "jdbc:oracle:thin:@192.168.1.110:1521:techdata";
private String USER = "tech";
private String PASSWORD = "tech";
private Connection con;
private PreparedStatement ps;
private Statement stm;
private ResultSet rs;
//构造函数
public DBAccess() {
try {
Class.forName(CLASSPATH);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//打开连接
public Connection getCon() {
try {
con = DriverManager.getConnection(URL,USER,PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
//建立一个陈述式对象用于执行静态SQL语句
public Statement getStmt() {
try {
stm = getCon().createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
return stm;
}
//建立预编译的SQL语句的对象
public PreparedStatement getPs(String sql) {
try {
ps = getCon().prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return ps;
}
//查询
public ResultSet executeQuery(String sql) {
try {
rs = getStmt().executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
//更新
public int executeUpdate(String sql) {
int result = 0;
try {
result = getStmt().executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
//打开事务
public void openTrans() {
try {
getCon().setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
//提交事务
public void commitTrans() {
try {
getCon().commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
//回滚事务
public void rollbackTrans() {
try {
getCon().rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
//关闭连接
public void close() {
if(rs!= null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stm != null) {
try {
stm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}