1:加载驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
2:获得链接
Connection co=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","scott","tiger");
3用PreparedStatement执行sql语句
查询语句用
executeQuery();
插入,修改,删除语句用
executeUpdate()
4:对执行结果的操作
5:关闭各种资源
package jdbctest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//数据库连接帮助类
public class DbHelp {
private Connection co;//连接属性
private PreparedStatement ps;//sql语句属性
private ResultSet rs;
public static DbHelp db=null;//判断数据库是否连接
public static DbHelp getDbHelp(){
if(db==null){
db=new DbHelp();
}
return db;
}
private DbHelp(){
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public int exeDml(String sql){
try {
co=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","scott","tiger");
ps=co.prepareStatement(sql);
return ps.executeUpdate(sql);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public ResultSet querry(String sql){
ResultSet rs=null;
try {
co=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","scott","tiger");
ps=co.prepareStatement(sql);
rs= ps.executeQuery();
} catch (SQLException e) {
throw new RuntimeException(e);
}
return rs;
}
public void closeResource(){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
rs=null;
throw new RuntimeException(e);
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
ps=null;
throw new RuntimeException(e);
}
}
if(co!=null){
try {
co.close();
} catch (SQLException e) {
co=null;
throw new RuntimeException(e);
}
}
}
}