当前位置:Gxlcms > 数据库问题 > 请允许我成为你的夏季——shiro、jdbcInsertall

请允许我成为你的夏季——shiro、jdbcInsertall

时间:2021-07-01 10:21:17 帮助过:11人阅读

/** 2 * 执行数据库插入操作 3 * 4 * @param datas 插入数据表中key为列名和value为列对应的值的Map对象的List集合 5 * @param tableName 要插入的数据库的表名 6 * @return 影响的行数 7 * @throws SQLException SQL异常 8 */ 9 public int insertAll(String tableName, List<Map<String, Object>> datas) throws SQLException { 10 /**影响的行数**/ 11 int affectRowCount = -1; 12 Connection connection = null; 13 PreparedStatement preparedStatement = null; 14 try { 15 /**从数据库连接池中获取数据库连接**/ 16 connection = getConnectionTwo(); 17 18 19 Map<String, Object> valueMap = datas.get(0); 20 /**获取数据库插入的Map的键值对的值**/ 21 Set<String> keySet = valueMap.keySet(); 22 Iterator<String> iterator = keySet.iterator(); 23 /**要插入的字段sql,其实就是用key拼起来的**/ 24 StringBuilder columnSql = new StringBuilder(); 25 /**要插入的字段值,其实就是?**/ 26 StringBuilder unknownMarkSql = new StringBuilder(); 27 Object[] keys = new Object[valueMap.size()]; 28 int i = 0; 29 while (iterator.hasNext()) { 30 String key = iterator.next(); 31 keys[i] = key; 32 columnSql.append(i == 0 ? "" : ","); 33 columnSql.append(key); 34 35 unknownMarkSql.append(i == 0 ? "" : ","); 36 unknownMarkSql.append("?"); 37 i++; 38 } 39 /**开始拼插入的sql语句**/ 40 StringBuilder sql = new StringBuilder(); 41 sql.append("INSERT INTO "); 42 sql.append(tableName); 43 sql.append(" ("); 44 sql.append(columnSql); 45 sql.append(" ) VALUES ("); 46 sql.append(unknownMarkSql); 47 sql.append(" )"); 48 49 /**执行SQL预编译**/ 50 preparedStatement = connection.prepareStatement(sql.toString()); 51 /**设置不自动提交,以便于在出现异常的时候数据库回滚**/ 52 connection.setAutoCommit(false); 53 System.out.println(sql.toString()); 54 for (int j = 0; j < datas.size(); j++) { 55 for (int k = 0; k < keys.length; k++) { 56 preparedStatement.setObject(k + 1, datas.get(j).get(keys[k])); 57 } 58 preparedStatement.addBatch(); 59 } 60 int[] arr = preparedStatement.executeBatch(); 61 connection.commit(); 62 affectRowCount = arr.length; 63 System.out.println("成功了插入了" + affectRowCount + "行"); 64 System.out.println(); 65 } catch (Exception e) { 66 if (connection != null) { 67 connection.rollback(); 68 } 69 e.printStackTrace(); 70 throw e; 71 } finally { 72 if (preparedStatement != null) { 73 preparedStatement.close(); 74 } 75 if (connection != null) { 76 connection.close(); 77 } 78 } 79 return affectRowCount; 80 }

 

 

晚安 时间不早了,2017年9月6日01:31:22,地点 公司。

请允许我成为你的夏季

   艾米莉?狄更生(美)

请允许我成为你的夏季,

当夏季的光阴已然流逝!

请允许我成为你的音乐,

当夜鹰与金莺收敛了歌喉!

请允许我为你绽放,我将穿越墓地,

四处播撒我的花朵!

请把我采撷吧——银莲花——

你的花朵——将为你盛开,直至永远!

 

请允许我成为你的夏季——shiro、jdbcInsertall

标签:toc   框架   www.   自己   提交   shu   list   end   next   

人气教程排行