JDBC
2017-06-22 本文已影响0人
陈俊亙
JDBC
- JDBC编程步骤
1.注册驱动
Class.forName(“com.mysql.jdbc.Driver”);
2.获取连接
DriverManager.getConnection(url,username,password);
3.创建statement对象
connection.createStatement();
4.执行sql
statement.executeQuery(sql); //select
statement.executeUpdate(sql); //update,delete,insert
5.遍历结果集
While(resultSet.next()){
resultSet.getXXX(columName/columIndex);
}
6.释放资源
需要放在finally代码块中.
Close();
- JDBCUtils
package cn.itcast.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtils {
private static String driver = "oracle.jdbc.OracleDriver";
private static String url = "jdbc:oracle:thin:@192.168.56.101:1521:orcl";
private static String user = "scott";
private static String password = "tiger";
static{
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection(){
try {
return DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/*
* 执行java程序
*/
public static void release(Connection conn,Statement st,ResultSet rs){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
rs = null;//why? ---> Java GC
}
}
if(st != null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
st = null;
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
conn = null;
}
}
}
}
- sql注入
- 解决了sql攻击(拼接)
- statment把sql语句发送给数据库,再编译执行.每次都发送,相同的语句会进行多次编译.
- preparedStatement预先编译,使用时填充数据,无需多次编译
Conection conn = JDBCUtils.getConnection();
String sql ="select * from user where username = ? and password = ?";
PreparedStatemnet ps = conn.prepareStatement(sql);
ps.setString(1,"xiaoming");
ps.setString(2,"666");
ResultSet rs = ps.execute(sql);
while(rs.next()){
}
- JDBC批处理
String sql1="";
String sql2="";
String sql3="";
st.addBatch(sq1);
st.addBatch(sq2);
st.addBatch(sq3);
st.executeBatch();
st.clearBatch();
-
JDBC事务
事务:控制业务逻辑的基本单元.事务管理的一组sql语句,要么都成功,要么都失败,不可分割.
成功commit,失败rollback
事务回滚点:理解成游戏的存档
try{
Connection conn = JDBCUtils.getConnection();
conn.setAutoCommit(false);
st = conn.createStatement();
st.executeUpdate("delete from user where name='xiaoming'");
int i=1/0;
conn.commit();
}catch(Exception e){
try {
con.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}