JDBC串連資料庫

來源:互聯網
上載者:User

標籤:虛擬   tchar   return   lock   env   getchar   靜態   系統   需要   

  1. ?建立一個以JDBC串連資料庫的程式,包含7個步驟:   
  2.  1、載入JDBC驅動程式:   
  3.     在串連資料庫之前,首先要載入想要串連的資料庫的驅動到JVM(Java虛擬機器),   
  4.     這通過java.lang.Class類的靜態方法forName(String  className)實現。   
  5.     例如:      
  6. static{
    try {
    //發布使用
    //Context context = new InitialContext(); //建立一個上下檔案對象
    //dataSource = (DataSource) context.lookup("java:comp/env/jdbc/jspJNDI");
    //開發中測試使用
    Properties props = new Properties();
    props.load(DbHelper.class.getClassLoader().getResourceAsStream("db.properties"));
    dataSource = BasicDataSourceFactory.createDataSource(props);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

  7.    成功載入後,會將Driver類的執行個體註冊到DriverManager類中。   
  8.  2、提供JDBC串連的URL   
  9.    ?串連URL定義了串連資料庫時的協議、子協議、資料來源標識。   
  10.     ?書寫形式:協議:子協議:資料來源標識   
  11.     協議:在JDBC中總是以jdbc開始   
  12.     子協議:是橋串連的驅動程式或是資料庫管理系統名稱。   
  13.     資料來源標識:標記找到資料庫來源的地址與串連連接埠。   
  14.     例如:(MySql的串連URL)   
  15.     jdbc:mysql:   
  16.         //localhost:3306/test?useUnicode=true&characterEncoding=gbk ;   
  17.    useUnicode=true:表示使用Unicode字元集。如果characterEncoding設定為   
  18.    gb2312或GBK,本參數必須設定為true 。characterEncoding=gbk:字元編碼方式。   
  19.  3、建立資料庫的串連   
  20.     ?要串連資料庫,需要向java.sql.DriverManager請求並獲得Connection對象,   
  21.      該對象就代表一個資料庫的串連。   
  22. //擷取資料庫連接對象
    public static Connection getConn(){
    Connection con = null;
    if (dataSource != null){
    try {
    con = dataSource.getConnection(); //在資料來源中取到一個串連
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    return con;
    }

  23.  4關閉連線物件
  24. public static void closeAll(ResultSet rs,Statement stmt,Connection conn ){
    //關閉結果集對象
    if(null!=rs){
    try {
    rs.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    //關閉語句對象
    if(null!=stmt){
    try {
    stmt.close();
    } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    //關閉資料庫連接對象
    if(null!=conn){
    try {
    conn.close();
    } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }

    public static void closeAll(ResultSet rs,PreparedStatement pstmt,Connection conn ){
    //關閉結果集對象
    if(null!=rs){
    try {
    rs.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    //關閉語句對象
    if(null!=pstmt){
    try {
    pstmt.close();
    } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    //關閉資料庫連接對象
    if(null!=conn){
    try {
    conn.close();
    } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }

  25.  5、設定參數的方法
  26. /**

  27. *@param pstmt 先行編譯對象

  28. * @param params 傳入的設定值的集合

  29. * @throws SQLException
    */
    private static void setParams(PreparedStatement pstmt,Object...params) throws SQLException{
    if(null!=params&&params.length>0){
    for(int i=0;i<params.length;i++){
    if(params[i] instanceof Date){
    //params儲存值的順序與 ?的順序一樣
    pstmt.setTimestamp(i+1, new Timestamp(((Date)params[i]).getTime()));
    }else{
    pstmt.setObject(i+1, params[i]);//params儲存值的順序與 ?的順序一樣
    }

    }
    }
    }

      
  30.  6、增刪改操作  
  31. /**
    * 增刪改
    * @param sql
    * @param params
    * @return
    * @throws SQLException
    */
    public static int doUpdate(String sql,Object...params) {
    Connection conn =null;
    PreparedStatement pstmt =null;
    int result =-1;

    try {
    conn=getConn();
    pstmt=conn.prepareStatement(sql);
    setParams(pstmt, params);
    result =pstmt.executeUpdate();
    } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }finally {
    closeAll(null, pstmt, conn);
    }
    return result;
    }

    public static int doUpdate(List<String> sqls, Object[]...params) throws SQLException{
    Connection conn =null;
    PreparedStatement pstmt =null;
    int result =-1;
    try {
    conn = getConn();
    conn.setAutoCommit(false);
    if(null!= sqls && sqls.size()>0){
    //迴圈sql語句
    for(int i=0;i<sqls.size();i++){
    String sql=sqls.get(i);
    pstmt =conn.prepareStatement(sql);
    //給當前sql語句設定
    setParams(pstmt, params[i]);
    result +=pstmt.executeUpdate();
    }
    }
    //提交事物
    conn.commit();
    } catch (Exception e) {
    e.printStackTrace();
    // 復原事物
    result=0;
    conn.rollback();
    } finally {
    //回複現場
    conn.setAutoCommit(true);
    closeAll(null, pstmt, conn);
    }
    return result;
    }

    public static int updateImg(String sql,int id ,File file) throws FileNotFoundException{
    FileInputStream in = new FileInputStream(file);
    Connection conn =null;
    PreparedStatement pstmt =null;
    int result = 0;
    try {
    pstmt = conn.prepareStatement(sql);
    pstmt.setBinaryStream(1, in,(int)file.length());
    pstmt.setInt(2, id);
    result = pstmt.executeUpdate();
    } catch (SQLException e) {

    } finally {
    closeAll(null, pstmt, conn);
    }

    return result;

  32. 6、查詢操作  

  33. /**
    * 查詢多條記錄
    * @param sql
    * @param params
    * @return
    * @throws SQLException
    */
    public static List<Map<String , Object>> findMultiObject(String sql,Object...params) throws SQLException{
    List<Map<String , Object>> list =new ArrayList<Map<String ,Object>>();
    Connection conn =null;
    PreparedStatement pstmt =null;
    ResultSet rs =null;
    Map<String, Object> map =null;
    try {
    conn =getConn();
    pstmt =conn.prepareStatement(sql);
    setParams(pstmt, params);
    rs =pstmt.executeQuery();
    List<String > columnNames =getAllColumnNames(rs);//擷取結果中的所有列表
    while(rs.next()){
    map = new HashMap<String,Object>();
    for(String cn:columnNames){//迴圈列名,將列表作用map的鍵,根據列表擷取到每個列的值
    map.put(cn, rs.getObject(cn));
    }
    list.add(map);
    }
    } finally {
    closeAll(rs, pstmt, conn);
    }

    return list;
    }

    /**
    * 查詢單條記錄 select * from 表名 where id = 1
    * @param sql
    * @param params
    * @return
    * @throws SQLException
    */
    public static Map<String,Object> findSingleObject(String sql, Object...params) throws SQLException{
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    Map<String,Object> map = null;
    try {
    conn = getConn();
    pstmt = conn.prepareStatement(sql);
    setParams(pstmt, params);
    rs = pstmt.executeQuery();
    List<String> columnNames = getAllColumnNames(rs); //擷取結果集中的所有列表
    while(rs.next()){
    map = new HashMap<String,Object>();
    for(String cn: columnNames){//迴圈列名,將列表作用Map的鍵,根據列表擷取到每個列的值
    map.put(cn, rs.getObject(cn));
    }
    }
    }finally{
    closeAll(rs, pstmt, conn);
    }
    return map;
    }

  34. 8、操作結果操作
    /**
    * 根據結果集對象擷取所有的列名 存在一個list集合中 jdbc2.0取中繼資料
    * @param rs
    * @return
    * @throws SQLException
    */
    private static List<String> getAllColumnNames(ResultSet rs ) throws SQLException{
    List<String> columnNames =new ArrayList<String>();
    if(null !=rs){
    for(int i=0 ;i<rs.getMetaData().getColumnCount();i++){
    columnNames.add(rs.getMetaData().getColumnName(i+1));
    }
    }
    return columnNames;
    }

    public static<T> T get(Class<T> clazz, String sql, Object...params) throws SQLException {
    return mapping2Obj(clazz, findSingleObject(sql, params));
    }

    public static <T> List<T> list(Class<T> clazz, String sql, Object...params) throws SQLException {
    List<Map<String , Object>> results = findMultiObject(sql, params);
    List<T> ts = null;
    if (results != null) {
    ts = new ArrayList<T>();
    for (Map<String, Object> result : results) {
    ts.add(mapping2Obj(clazz, result));
    }
    }
    return ts;
    }

    private static <T> T mapping2Obj(Class<T> clazz, Map<String,Object> temps){
    T t = null;
    try {
    t = clazz.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
    e.printStackTrace();
    }
    Method[] ms = clazz.getDeclaredMethods(); //取到所有的方法
    for (Method m : ms) {
    String mn = m.getName(); //取到方法名
    if(mn.startsWith("set")){
    String pt = m.getParameterTypes()[0].getName(); //取到set方法的參數類型
    Object obj = temps.get(mn.replace("set", "").toUpperCase()); //取到set方法對應資料庫欄位的值
    try {
    if(obj != null){
    if (pt.endsWith("int") || pt.endsWith("Integer")) {
    m.invoke(t, ((BigDecimal)obj).intValue());
    } else if (pt.endsWith("double") || pt.endsWith("Double")) {
    m.invoke(t, ((BigDecimal)obj).doubleValue());
    } else if (pt.endsWith("java.util.Date")) {
    m.invoke(t, (Timestamp)obj); //11g
    //m.invoke(t, new Date(((java.sql.Date)obj).getTime())); //10g
    } else {
    if(obj.getClass().getName().endsWith("CLOB")){
    obj = clobToString((CLOB)obj);
    }
    m.invoke(t, obj);
    }
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    return t;
    }

    public static String clobToString(Clob clob) {
    String reString = "";
    Reader is = null;
    try {
    is = clob.getCharacterStream();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    // 得到流
    BufferedReader br = new BufferedReader(is);
    String s = null;
    try {
    s = br.readLine();
    } catch (IOException e) {
    e.printStackTrace();
    }
    StringBuffer sb = new StringBuffer();
    while (s != null) {
    //執行迴圈將字串全部取出付值給StringBuffer由StringBuffer轉成STRING
    sb.append(s);
    try {
    s = br.readLine();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    reString = sb.toString();
    return reString;
    }
    }

JDBC串連資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.