zoukankan      html  css  js  c++  java
  • DBHelper--Java JDBC SSH 连接数据库工具类

    概述

     JDBC 指 Java 数据库连接,是一种标准Java应用编程接口( JAVA API),用来连接 Java 编程语言和广泛的数据库。

    -------------------------------------------------------淫荡的分割线-------------------------------------------------------

    简单使用

    使用JDBC需要以下几个步骤:

    1. 加载JDBC驱动程序
    2. 提供JDBC连接的URL
    3. 创建数据库连接
    4. 创建一个Statement对象
    5. 执行SQL语句
    6. 处理返回结果
    7. 关闭数据库连接

    废话少说,上代码

      1 package com.aicai.qa.tools.statics;
      2 
      3 import com.aicai.qa.tools.statics.config.SysConfigUtil;
      4 
      5 import java.sql.*;
      6 
      7 /**
      8  * @author tengfei
      9  * @version 1.0
     10  * @date 2018/7/15 下午8:32
     11  */
     12 public class DBHelper {
     13     private static DBHelper dbHelper=null;
     14 
     15     private String host;
     16 
     17     private Integer port;
     18 
     19     private String dataBaseName;
     20 
     21     private String jdbcDriver;
     22 
     23     private String userName;
     24 
     25     private String password;
     26 
     27     private String jdbcConnectionStr;
     28 
     29     private Connection connection;
     30 
     31     private PreparedStatement preparedStatement;
     32 
     33     private ResultSet resultSet;
     34 
     35     private DBHelper() {
     36         this.host = SysConfigUtil.getSysConfigUtil("jdbc.properties").getString("jdbc.host");
     37         this.port = SysConfigUtil.getSysConfigUtil("jdbc.properties").getInt("jdbc.port");
     38         this.dataBaseName = SysConfigUtil.getSysConfigUtil("jdbc.properties").getString("jdbc.dataBaseName");
     39         this.userName = SysConfigUtil.getSysConfigUtil("jdbc.properties").getString("jdbc.userName");
     40         this.password = SysConfigUtil.getSysConfigUtil("jdbc.properties").getString("jdbc.password");
     41         this.jdbcDriver = SysConfigUtil.getSysConfigUtil("jdbc.properties").getString("jdbc.driver");
     42         jdbcConnectionStr = String.format("jdbc:mysql://%s:%s/%s", host, port, dataBaseName);
     43     }
     44 
     45     public static DBHelper createDBHelper() {
     46         dbHelper = new DBHelper();
     47         dbHelper.initDB();
     48         return dbHelper;
     49     }
     50 
     51 
     52     public void getConn() {
     53         try {
     54             connection = DriverManager.getConnection(jdbcConnectionStr, userName, password);
     55             connection.setAutoCommit(false);
     56         } catch (SQLException e) {
     57             e.printStackTrace();
     58         }
     59     }
     60 
     61     public void close() {
     62         if (resultSet != null) {
     63             try {
     64                 resultSet.close();
     65                 if (preparedStatement != null) {
     66                     preparedStatement.close();
     67                 }
     68                 if (connection != null) {
     69                     connection.close();
     70                 }
     71             } catch (SQLException e) {
     72                 e.printStackTrace();
     73             }
     74         }
     75     }
     76 
     77     public ResultSet executeQuery(String sql, Object[] params) {
     78         dbHelper.setPrepareStatementParams(sql, params);
     79         try {
     80             resultSet = preparedStatement.executeQuery();
     81         } catch (SQLException e) {
     82             e.printStackTrace();
     83         }
     84         return resultSet;
     85     }
     86 
     87     public Boolean executeUpdate(String sql, Object[] params) {
     88         boolean result = false;
     89         dbHelper.setPrepareStatementParams(sql, params);
     90         try {
     91             if (preparedStatement.executeUpdate() > 0) {
     92                 dbHelper.commit();
     93                 result = true;
     94             }
     95         } catch (SQLException e) {
     96             e.printStackTrace();
     97         }
     98         return result;
     99     }
    100 
    101     @SuppressWarnings("unused")
    102     private void setPrepareStatementParams(String sql, Object[] params) {
    103         try {
    104             preparedStatement = connection.prepareStatement(sql);
    105             if (params != null) {
    106                 for (int i = 0; i < params.length; i++) {
    107                     preparedStatement.setObject((i + 1), params[i]);
    108                 }
    109             }
    110         } catch (SQLException e) {
    111             e.printStackTrace();
    112         }
    113     }
    114 
    115     private void initDB() {
    116         try {
    117             Class.forName(jdbcDriver);
    118         } catch (ClassNotFoundException e) {
    119             e.printStackTrace();
    120         }
    121     }
    122 
    123     private void commit() {
    124         try {
    125             connection.commit();
    126         } catch (SQLException e) {
    127             e.printStackTrace();
    128         }
    129     }
    130 
    131     public static void main(String[] args) throws SQLException {
    132         dbHelper = DBHelper.createDBHelper();
    133         dbHelper.getConn();
    134         String sql = "SELECT * FROM productCases";
    135         ResultSet resultSet = dbHelper.executeQuery(sql,null);
    136         while (resultSet.next()){
    137             for (int i = 0; i < resultSet.getMetaData().getColumnCount(); i++) {
    138                 System.out.println(resultSet.getMetaData().getCatalogName(i+1)+":"+resultSet.getString(i+1));
    139             }
    140         }
    141     }
    142 }

    -------------------------------------------------------淫荡的分割线-------------------------------------------------------

    SSH管道以及迭代器模式使用

    1. JSch介绍:JSch是一个SSH2的纯Java实现。它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,当然你也可以集成它的功能到你自己的应用程序。要使用JSch,需要下载它的jar包,请从官网下载它:http://www.jcraft.com/jsch/
    2. JSch连接MySQL数据库小栗子:
    package com.aicai.qa.tools.statics.db;
    
    import com.aicai.qa.tools.statics.db.vo.DbVO;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.JSchException;
    import com.jcraft.jsch.Session;
    import lombok.extern.slf4j.Slf4j;
    
    import java.sql.*;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    
    /**
     * @author tengfei
     * @version 1.0
     * @date 2018/7/10 下午5:06
     */
    @Slf4j
    public class DBHelper implements Iterator<Object[]> {
        private static JSch jSch = new JSch();
        ResultSet rs;
        ResultSetMetaData rd;
        Connection connection;
        Statement statement;
        private String url;
        private Integer current = 0;
        private Integer readIndex = 0;
    
        public DBHelper(DbVO db, String sql) {
            log.info("DBHelper exec");
            try {
                if (db != null) {
                    if (db.getBindingPort() != null) {
                        Session session = jSch.getSession(db.getSshName(), db.getSshIp(), db.getSshPort());
                        session.setPassword(db.getSshPwd());
                        session.setConfig("StrictHostKeyChecking", "no");
                        session.connect();
                        session.setPortForwardingL(db.getBindingPort(), db.getIp(), db.getPort());
                        url = String.format("jdbc:mysql://localhost:%s/%s", db.getBindingPort(), db.getBaseName());
                    } else {
                        url = String.format("jdbc:mysql://%s:%s/%s", db.getIp(), db.getPort(), db.getBaseName());
                    }
                    Class.forName("com.mysql.jdbc.Driver");
                    connection = DriverManager.getConnection(url, db.getUserName(), db.getPassword());
                    statement = connection.createStatement();
                    rs = statement.executeQuery(sql);
                    rd = rs.getMetaData();
                }
            } catch (JSchException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    
        @Override
        public boolean hasNext() {
            log.info("hasNext method exec");
            boolean flag = false;
            if (readIndex < current) {
                return true;
            }
            try {
                flag = rs.next();
                current++;
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return flag;
        }
    
        @Override
        public Object[] next() {
            log.info("next method exec");
            readIndex++;
            Map<String, String> data = new HashMap<>(16);
            try {
                for (int i = 0; i < rd.getColumnCount(); i++) {
                    data.put(rd.getColumnName(i + 1), rs.getString(i + 1));
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            Object[] rows = new Object[1];
            rows[0] = data;
            return rows;
        }
    
        @Override
        public void remove() {
            free(rs, statement, connection);
        }
    
        private static void free(ResultSet rs) {
            close(rs);
        }
    
        private static void free(ResultSet rs, Statement statement) {
            free(rs);
            close(statement);
        }
    
        private static void free(ResultSet rs, Statement statement, Connection connection) {
            free(rs, statement);
            close(connection);
        }
    
        private static void close(ResultSet rs) {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    log.error("closed ResultSet object fail.localized message is {}", e.getLocalizedMessage());
                }
            }
        }
    
        private static void close(Statement statement) {
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    log.error("closed Statement object fail.localized message is {}", e.getLocalizedMessage());
                }
            }
        }
    
        private static void close(Connection connection) {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    log.error("closed Connection object fail.localized message is {}", e.getLocalizedMessage());
                }
            }
        }
    
    }
  • 相关阅读:
    设置开机启动时指定非ROOT用户执行相应的脚本
    passwd的使用
    redis安装过程中遇到的问题
    linux增大交换分区
    初学Pexpect
    系统吞吐量(TPS)、用户并发量、性能测试概念和公式
    CentOS系统下各文件夹的作用
    Python的学习
    syntax error near unexpected token `then'
    10.24 小组会议记录
  • 原文地址:https://www.cnblogs.com/tengfly/p/9315302.html
Copyright © 2011-2022 走看看