1. 程式人生 > >c3p0 一個數據庫鏈接的例子

c3p0 一個數據庫鏈接的例子

pan cto on() span 方法參數 內存溢出 tar subst blank

首先需要準備三個依賴包 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 }

c3p0 一個數據庫鏈接的例子