JDBC连接数据库

来源:互联网 发布:童瑶的知乎回答 编辑:程序博客网 时间:2024/04/29 10:39

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;

public class BaseDao {
public Connection conn;
public PreparedStatement pst;
public ResultSet rst;

static{    try {        Class.forName("oracle.jdbc.driver.OracleDriver");    } catch (Exception e) {        e.printStackTrace();    }}public Connection getConn(){    String url="jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=xx)(PORT=xxx)))(CONNECT_DATA=(SERVICE_NAME=msi)(SERVER=DEDICATED)))";    try {        conn=DriverManager.getConnection(url,"xx","xxx");    } catch (Exception e) {        // TODO: handle exception        e.printStackTrace();    }    return conn;}public void closeAll(Connection conn,PreparedStatement pst,ResultSet rst){    try {        if (rst!=null) {            rst.close();        }        if (pst!=null) {            pst.close();        }        if (conn!=null) {            conn.close();        }    } catch (Exception e) {        e.printStackTrace();    }}public int excuteUpdate(String sql,Object[] arr){    int cc=-1;    try {        conn=getConn();        pst=conn.prepareStatement(sql);        if (arr!=null&&arr.length!=0) {            for (int i = 0; i < arr.length; i++) {                if (arr[i] instanceof Timestamp) {                    pst.setTimestamp(i+1, (Timestamp) arr[i]);                }else{                    pst.setObject(i+1, arr[i]);                }            }        }        System.out.println(sql);        pst.executeUpdate();        conn.commit();    } catch (Exception e) {        // TODO: handle exception        e.printStackTrace();    }    finally{        closeAll(conn, pst, rst);    }    return cc;}

}

0 0
原创粉丝点击