• c3p0 一个数据库链接的例子


    首先需要准备三个依赖包 c3p0-0.9.5.2.jar、mchange-commons-java-0.2.11.jar、mysql-connector-java-5.1.47.jar

    下载链接 https://files.cnblogs.com/files/ruber/lib.rar

      1 public class testMysql implements myRoot{
      2     private ComboPooledDataSource dataSource = null;
      3 //    private Connection connection = null;
      4     @Override
      5     public void done() {
      6         initMysql();
      7         
      8         Connection connection = getConnection();//获取自动提交数据库连接
      9         setAutoCommit(connection, true);
     10         
     11         String name = doSql(connection, String.class, "select playerName from t_player where playerId = ?", 2);
     12         System.out.println("name = " + name);
     13         
     14         tplayer player = doSql(connection, tplayer.class, "select * from t_player where playerId = ?", 2);
     15         
     16         System.out.println("getPlayerId = " + player.getPlayerId());
     17         System.out.println("getPlayerName = " + player.getPlayerName());
     18         System.out.println("getCreateTime = " + player.getCreateTime());
     19         System.out.println("getLoginTime = " + player.getLoginTime());
     20         System.out.println("getLogoutTime = " + player.getLogoutTime());
     21         
     22         //--------批量提交sql-------------
     23         
     24         String Ary[] = new String[2];
     25         Ary[0] = "UPDATE t_player SET playerName = "ccc" WHERE playerId = 3;";
     26         Ary[1] = "UPDATE t_player SET playerName = "ddd" WHERE playerId = 4;";
     27         
     28         batchSql(connection, Ary);
     29         closeConnection(connection);//关闭连接
     30         
     31     }
     32     //批量提交处理事务
     33     public void batchSql(Connection connection, String []Ary){
     34         Statement st = null;
     35         try {
     36             setAutoCommit(connection, false);//必须为false,否则java.sql.SQLException: Can't call commit when autocommit=true
     37             st = connection.createStatement();
     38             
     39             int c=0;
     40             for(String sql:Ary){
     41                 st.addBatch(sql);
     42                 c++;
     43                 if(c == 1000){//防止内存溢出,一次不要提交太多条,暂设1000条
     44                     st.executeBatch();
     45                     commit(connection);
     46                     st.clearBatch();
     47                     c=0;
     48                 }
     49                 if(c>0){
     50                     st.executeBatch();
     51                     commit(connection);
     52                     st.clearBatch();
     53                 }
     54             }
     55             
     56         } catch (SQLException e) {
     57             e.printStackTrace();
     58         }finally{
     59             setAutoCommit(connection, true);
     60             closeStateMent(st);
     61         }
     62     }
     63     
     64     /**
     65      * @param cls 返回类型类
     66      * @param sql sql语句
     67      * @param paramter sql语句参数
     68      * @return cls实例
     69      */
     70     @SuppressWarnings("unchecked")
     71     public <T>T doSql(Connection connection, Class<?> cls, String sql, Object... paramter){
     72         PreparedStatement pst = null;
     73         ResultSet rs = null;
     74         
     75         Object obj = null;
     76         try {
     77             pst = connection.prepareStatement(sql);//创建一个 PreparedStatement 对象来将参数化的 SQL 语句发送到数据库
     78             if(paramter != null && paramter.length  > 0){
     79                 int i=1;//从1开始
     80                 for(Object parm: paramter){
     81                     pst.setObject(i++, parm);//为sql语句设置参数 
     82                 }
     83             }
     84             rs = pst.executeQuery();//执行语句,返回ResultSet结果
     85             while(rs.next()){
     86                 if(cls.getSimpleName().toLowerCase().equals("string")){//标准类型
     87                     obj = rs.getString(1);
     88                 }else{//自定义类型
     89                     obj = cls.newInstance();//创建自定义类型
     90                     ResultSetMetaData resultsetmetadata = rs.getMetaData();//整行列信息
     91                     int count = resultsetmetadata.getColumnCount();//列数量
     92                     for(int i=1; i<=count; i++){//从1开始
     93                         String columnlabel = resultsetmetadata.getColumnLabel(i);//当前列标头
     94                         String methName = "set" + columnlabel.substring(0, 1).toUpperCase() + columnlabel.substring(1);//自定义类型的方法名,次数为set方法
     95                         
     96                         Method[] methods = cls.getDeclaredMethods();//自定义类型的方法数组
     97                         int methodsSize = methods.length;//方法数量
     98                         for(int j=0; j<methodsSize; j++){
     99                             if(methods[j].getName().equals(methName)){
    100                                 Parameter[] parameterAry = methods[j].getParameters();//获取方法参数数组
    101                                 Class<?> type = parameterAry[0].getType();//第一个参数类型 从0开始
    102                                 String typeName = type.getSimpleName().toLowerCase();//参数类型的名字
    103 //                                String typeName = methods[j].getParameters()[0].getType().getSimpleName().toLowerCase();//这种写法不被推荐
    104                                 //反射调用
    105                                 if(typeName.equals("int")){
    106                                     methods[j].invoke(obj, rs.getInt(i));
    107                                 }else if(typeName.equals("string")){
    108                                     methods[j].invoke(obj, rs.getString(i));
    109                                 }
    110                             }
    111                         }
    112                     }
    113                 }
    114             }
    115         } catch (Exception e) {
    116             e.printStackTrace();
    117         }finally{
    118             try {
    119                 if(pst != null){ pst.close(); }
    120                 if( rs != null){ rs.close();  }
    121             } catch (SQLException e) {
    122                 e.printStackTrace();
    123             }
    124         }
    125         return (T) obj;
    126     }
    127     public void initMysql(){
    128         
    129         dataSource = new ComboPooledDataSource();
    130         try {
    131             dataSource.setDriverClass("com.mysql.jdbc.Driver");//com.mysql.jdbc.Driver
    132         } catch (PropertyVetoException e) {
    133             e.printStackTrace();
    134         }
    135         dataSource.setJdbcUrl("jdbc:mysql://192.168.50.229:3306/banzhan_tplayer?autoReconnect=true&rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf-8&useSSL=false");//
    136         dataSource.setUser("root");//root
    137         dataSource.setPassword("123456");//123456
    138         dataSource.setInitialPoolSize(1);//5 数量机器相关
    139         dataSource.setMinPoolSize(1);
    140         dataSource.setMaxPoolSize(1);
    141         dataSource.setTestConnectionOnCheckin(true);        //每次获取connection测试其有效性
    142         dataSource.setAutomaticTestTable("C3P0TestTable");    //测试表
    143         dataSource.setIdleConnectionTestPeriod(360);        //每N秒检查一次空闲连接
    144         dataSource.setMaxIdleTime(720);    
    145     }
    146     
    147     public Connection getConnection(){
    148         Connection connection = null;
    149         if(dataSource != null){
    150             try {
    151                 connection =  dataSource.getConnection();
    152             } catch (SQLException e) {
    153                 e.printStackTrace();
    154             }
    155         }
    156         return connection;
    157     }
    158     
    159     public void setAutoCommit(Connection connection, boolean autoCommit){
    160         
    161         try {
    162             connection.setAutoCommit(autoCommit);
    163         } catch (SQLException e) {
    164             e.printStackTrace();
    165         }
    166         
    167     }
    168     
    169     public void commit(Connection connection){
    170         try {
    171             connection.commit();
    172         } catch (SQLException e) {
    173             e.printStackTrace();
    174         }
    175     }
    176     public void closeStateMent(Statement pst){
    177         if(pst != null){
    178             try {
    179                 pst.close();
    180             } catch (SQLException e) {
    181                 e.printStackTrace();
    182             }
    183         }
    184     }
    185     
    186     public void closeConnection(Connection connection){
    187         try {
    188             if(connection != null){
    189                 connection.close();
    190             }
    191         } catch (SQLException e) {
    192             e.printStackTrace();
    193         }
    194     }
    195 }
  • 相关阅读:
    注册tomcat为服务
    BootStrap
    Passive DNS
    一个插件平台
    HDU 4394 BFS
    设计模式--组合模式--商品排序案例
    Windows平台编译openssl-0.9.8k库(32位、64位)
    JavaScript之this释疑
    OpenLayers3基础教程——OL3 介绍control
    我的Android进阶之旅------&gt; Android为TextView组件中显示的文本加入背景色
  • 原文地址:https://www.cnblogs.com/ruber/p/10297980.html
Copyright © 2020-2023  润新知