JDBC

2017-06-22  本文已影响0人  陈俊亙

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();
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;
            }
        }
    }
}
    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()){
        }
    String sql1="";
    String sql2="";
    String sql3="";
    st.addBatch(sq1);
    st.addBatch(sq2);
    st.addBatch(sq3);
    st.executeBatch();
    st.clearBatch();
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();
    }
上一篇下一篇

猜你喜欢

热点阅读