当前位置:   article > 正文

MysqlUtil 5.3.1.3_mysqlutil.mysqlutil.insertdata

mysqlutil.mysqlutil.insertdata
  1. package com.jfai.util;
  2. import java.io.InputStream;
  3. import java.io.Reader;
  4. import java.math.BigDecimal;
  5. import java.sql.Blob;
  6. import java.sql.Clob;
  7. import java.sql.Connection;
  8. import java.sql.NClob;
  9. import java.sql.PreparedStatement;
  10. import java.sql.ResultSet;
  11. import java.sql.SQLException;
  12. import java.sql.Statement;
  13. import java.util.ArrayList;
  14. import java.util.Arrays;
  15. import java.util.LinkedHashMap;
  16. import java.util.LinkedList;
  17. import java.util.List;
  18. import java.util.Map;
  19. import java.util.Random;
  20. import javax.sql.DataSource;
  21. /**
  22. apache.commons.lang 工具包,可以在maven中添加如下依赖获取
  23. <dependency>
  24. <groupId>commons-lang</groupId>
  25. <artifactId>commons-lang</artifactId>
  26. <version>2.6</version>
  27. </dependency>
  28. google的Gson工具包,可以在maven中添加如下依赖获取
  29. <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
  30. <dependency>
  31. <groupId>com.google.code.gson</groupId>
  32. <artifactId>gson</artifactId>
  33. <version>2.8.5</version>
  34. </dependency>
  35. druid连接池包,可以在maven中添加如下依赖获取
  36. <dependency>
  37. <groupId>com.alibaba</groupId>
  38. <artifactId>druid</artifactId>
  39. <version>1.1.10</version>
  40. </dependency>
  41. */
  42. import org.apache.commons.lang.ArrayUtils;
  43. import com.alibaba.druid.pool.DruidDataSource;
  44. import com.alibaba.druid.sql.SQLUtils;
  45. import com.google.gson.JsonObject;
  46. import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
  47. import lombok.extern.slf4j.Slf4j;
  48. /**
  49. * @author wanglf
  50. * @version 5.3.1.3
  51. * @Package com.jfai.kg.dao.impl
  52. * @Description: MysqlUtil
  53. * @date 2018年7月9日 上午10:52:04
  54. * @Attention
  55. * 为避免某些神奇的使用各种null做表名和参数的使用情况, 所以为空校验全部调为Blank级别
  56. * 关于参数非法的时候返回空对象还是null的问题,现在的策略是如果返回的对象是集合,则返回空的集合,其他则返回null(注:这样主要是为了调用的时候拿到集合返回对象,直接就可以遍历,不用判断null)
  57. * 如果没有规定明确要传schemaName参数,tableName参数可以是 库名.表名 的格式,从而对其他的库进行操作
  58. * mysql的bigint类型本身就包含了8个字节的长度,指定的长度只是指定显示宽度,不影响存储。所以无论是bigint(10),还是bigint(20)均占用8个字节
  59. * @remark
  60. * 修复表名``画蛇添爪爪 问题 2018年7月19日21:09:44
  61. * 增强并调整log显示功能 2018年7月22日22:14:12
  62. * 新增private方法,解除对StringUtil类方法的依赖 2018年7月26日16:00:40
  63. * 增强并调整log显示功能 2018年7月31日11:33:12
  64. * 新增getBuildSQL方法 2018年7月31日12:12:21
  65. * 新增execute方法 2018年7月31日12:28:02
  66. * 新增getSchemas 获取数据库名的集合 功能 2018年7月31日14:05:11
  67. * 新增List 插入 内包含批处理 2018年7月31日16:30:39
  68. * 新增id相关的delete方法并更新注释 2018年7月31日17:51:52
  69. * 新增批量添加列功能列名修改功能和原新增列功能增强 2018年7月31日18:59:23
  70. * 插入jsonOnbject的时候,新增忽略id功能(主要用来插入数据时目标表,有自己的主键生成策略的情况) 2018年8月3日19:32:39
  71. * 新增依据id和idList查询数据功能 2018年8月5日13:40:43
  72. * 新增入口方法欢迎 2018年8月5日14:37:47
  73. * 调整getTableInfo方法,新增列信息获取方法 2018年8月7日09:55:25
  74. * 新增isPrimaryKey和调整并增强getColumnInfo方法 2018年8月8日19:50:00
  75. * 集成JDBCUtil的功能,新增关闭连接和资源的方法 2018年8月8日20:15:52
  76. * 集成DataSourceSingleton,新增获取数据源和获取连接功能 2018年8月8日21:12:18
  77. * 新增setParam方法,可以将有占位符的SQL还原为可执行的SQL 2018年8月11日19:23:25
  78. */
  79. @Slf4j
  80. public class MysqlUtil {
  81. private static DruidDataSource dataSource = new DruidDataSource();
  82. /**
  83. * 私有化构造方法,工具类禁止new对象
  84. */
  85. private MysqlUtil() {
  86. }
  87. /**
  88. * 调用该方法可以返回一个mysql的数据源
  89. * 目前使用的是阿里的Druid连接池
  90. *
  91. * @return
  92. * @version 1.0.0
  93. * @remark 也可以作为单例模式的另一种实现, 因为只New了一个DataSource
  94. */
  95. public static DataSource getDataSource() {
  96. return dataSource;
  97. }
  98. /**
  99. * 获取数据库连接
  100. */
  101. public static Connection getConnection() {
  102. try {
  103. return dataSource.getConnection();
  104. } catch (SQLException e) {
  105. log.error("Exception :", e);
  106. }
  107. return null;
  108. }
  109. /**
  110. * 初始化mysql数据库,优化mysql数据库设置
  111. *
  112. * @version 1.0.0
  113. * @Description 设置mysql的最大并发连接数为5000
  114. * 设置mysql的缓冲中间表的size=256M
  115. * 设置mysql缓冲区大小=32M
  116. * 设置mysql允许接收的的最大数据包尺寸为16M
  117. * @remark 可能涉及了一点mysql的数据库调优
  118. */
  119. public static void init() {
  120. log.info("{}.{} Welcome to your arrival!", Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getMethodName());
  121. long t1 = System.currentTimeMillis();
  122. Connection conn = null;
  123. Statement stm = null;
  124. ResultSet rs = null;
  125. // 设置mysql的最大并发连接数为5000,并发连接数设小了,坑.. 虽然一般用不到5000
  126. String sql = "set GLOBAL max_connections =5000";
  127. // 设置mysql的缓冲中间表的size,不然涉及列操作的时候,可能会出现二次读写,特别是百万数据大表,那速度 ...
  128. String sql_1 = "set GLOBAL tmp_table_size =256*1024*1024";// -- 256M
  129. // 设置mysql缓冲区大小
  130. String sql_2 = "set GLOBAL read_buffer_size =32*1024*1024";// -- 32M
  131. // 设置mysql允许的最大的一次可允许接收数据量,不然大数据量批处理操作,你懂得 ..
  132. String sql_3 = "set GLOBAL max_allowed_packet = 16*1024*1024";// -- 16M
  133. try {
  134. conn = dataSource.getConnection();
  135. conn.setAutoCommit(false);
  136. stm = conn.createStatement();
  137. stm.addBatch(sql);
  138. stm.addBatch(sql_1);
  139. stm.addBatch(sql_2);
  140. stm.addBatch(sql_3);
  141. stm.executeBatch();
  142. conn.commit();// 执行完后,手动提交事务,不然会回滚
  143. conn.setAutoCommit(true);// 再把自动提交打开
  144. long t2 = System.currentTimeMillis();
  145. log.info("MysqlUtil.init>>执行SQL完毕!, 耗时: {}ms", sql.toUpperCase(), t2 - t1);
  146. } catch (Exception e) {
  147. try {
  148. conn.rollback();
  149. log.error("MysqlUtil.init log error!", e);
  150. } catch (SQLException e1) {
  151. log.error("Exception :", e1);
  152. }
  153. } finally {
  154. close(rs, stm, conn);
  155. }
  156. }
  157. /**
  158. * 关闭相关资源,并返回连接
  159. *
  160. * @param rs java.sql.ResultSet 数据库结果集
  161. * @param s java.sql.Statement SQL执行体
  162. * @param connection java.sql.Connection 数据库连接
  163. * @version 1.0.0
  164. */
  165. public static void close(ResultSet rs, Statement s, Connection connection) {
  166. clostResultSet(rs);
  167. clostStatement(s);
  168. clostConnection(connection);
  169. }
  170. /**
  171. * 关闭ResultSet
  172. *
  173. * @param rs java.sql.ResultSet
  174. * @version 1.0.0
  175. * @Attention
  176. */
  177. public static void clostResultSet(ResultSet rs) {
  178. if (rs != null) {
  179. try {
  180. rs.close();
  181. } catch (Exception e) {
  182. log.error("Exception :", e);
  183. }
  184. }
  185. }
  186. /**
  187. * 关闭Statement 注:PreparedStatement也可以用该方法关闭
  188. *
  189. * @param s java.sql.Statement
  190. * @version 1.0.0
  191. * @remark PreparedStatement是Statement的子类, 所以也可以使用该方法关闭
  192. */
  193. public static void clostStatement(Statement s) {
  194. if (s != null) {
  195. try {
  196. s.close();
  197. } catch (Exception e) {
  198. log.error("Exception :", e);
  199. }
  200. }
  201. }
  202. /**
  203. * 返回连接到连接池,如果未使用连接池,则会直接关闭连接
  204. *
  205. * @param conn
  206. * @version 1.0.0
  207. * @Attention 如果未使用连接池, 则会直接关闭连接
  208. * 如果使用连接池,会将连接返回连接池
  209. */
  210. public static void clostConnection(Connection conn) {
  211. if (conn != null) {
  212. try {
  213. conn.close();
  214. } catch (Exception e) {
  215. log.error("Exception :", e);
  216. }
  217. }
  218. }
  219. /**
  220. * 向指定的表插入数据,数据类型为map 的key-value形式
  221. *
  222. * @param dataMap 要插入的数据集
  223. * @param tableName 表名
  224. * @return true or false
  225. */
  226. public static boolean add(Map<String, Object> dataMap, String tableName) {
  227. return insert(dataMap, tableName);
  228. }
  229. /**
  230. * 向指定的表插入数据,数据类型为map 的key-value形式
  231. *
  232. * @param dataMap 要插入的数据集
  233. * @param tableName 表名
  234. * @return true or false
  235. */
  236. public static boolean insert(Map<String, Object> dataMap, String tableName) {
  237. log.info("{}.{} Welcome to your arrival!", Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getMethodName());
  238. if (tableName == null || tableName.length() == 0) {
  239. log.error("MysqlUtil.insert Parameter[tableName] is empty ! Return!");
  240. return false;
  241. }
  242. if (dataMap == null || dataMap.size() == 0) {
  243. log.error("MysqlUtil.insert Parameter[dataMap] is empty ! Return!");
  244. return false;
  245. }
  246. long t1 = System.currentTimeMillis();
  247. Connection conn = null;
  248. PreparedStatement pstm = null;
  249. ResultSet rs = null;
  250. StringBuilder sql = new StringBuilder();
  251. StringBuilder p = new StringBuilder();
  252. // Object[] args = new Object[dataMap.size()];
  253. sql.append("insert into " + tableName + "( ");
  254. // int i = 0;
  255. // for (String aName : dataMap.keySet()) {
  256. // if (i != dataMap.size() - 1) {
  257. // sql.append(aName + ",");
  258. // p.append("?,");
  259. // } else {
  260. // sql.append(aName);
  261. // p.append("?");
  262. // }
  263. // args[i] = dataMap.get(aName);
  264. // i++;
  265. // }
  266. // sql.append(") values(").append(p).append(")");
  267. List<Object> params =new LinkedList<Object>();
  268. for (String aName : dataMap.keySet()) {
  269. sql.append(aName + ",");
  270. p.append("?,");
  271. params.add(dataMap.get(aName));
  272. }
  273. sql.deleteCharAt(sql.length()-1).append(") values(").append(p.deleteCharAt(p.length()-1)).append(")");
  274. int re = 0;
  275. try {
  276. conn = dataSource.getConnection();
  277. sql=new StringBuilder((setParam(params, sql.toString())));
  278. pstm = conn.prepareStatement(sql.toString());
  279. // for (int k = 0; k < args.length; k++) {
  280. // pstm.setObject(k + 1, args[k]);
  281. // }
  282. re = pstm.executeUpdate();
  283. long t2 = System.currentTimeMillis();
  284. log.info("MysqlUtil.insert>>执行SQL: {}, 耗时: {}ms", sql.toString(), t2 - t1);
  285. //log.info("MysqlUtil.insert>>传入的参数值arg=>{}", Arrays.toString(args));
  286. } catch (Exception e) {
  287. log.error("MysqlUtil.insert>>执行SQL: {}", sql);
  288. //log.error("MysqlUtil.insert>>传入的参数值arg=>{}", Arrays.toString(args));
  289. log.error("MysqlUtil.insert log error!", e);
  290. } finally {
  291. close(rs, pstm, conn);
  292. }
  293. return re == 0 ? false : true;
  294. }
  295. /**
  296. * @param dataMap 要更改的值map
  297. * @param condition where条件值 key-value形式,用map包装
  298. * @param tableName 表名 可以为库名.表名形式
  299. * @return true or false
  300. */
  301. public static boolean update(Map<String, Object> dataMap, Map<String, Object> condition, String tableName) {
  302. log.info("{}.{} Welcome to your arrival!", Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getMethodName());
  303. if (tableName == null || tableName.length() == 0) {
  304. log.error("MysqlUtil.update Parameter[tableName] is empty ! Return!");
  305. return false;
  306. }
  307. if (dataMap == null || dataMap.size() == 0) {
  308. log.error("MysqlUtil.update Parameter[dataMap] is empty ! Return!");
  309. return false;
  310. }
  311. if (condition == null || condition.size() == 0) {
  312. log.error("MysqlUtil.update Parameter[condition] is empty ! Return!");
  313. return false;
  314. }
  315. long t1 = System.currentTimeMillis();
  316. Connection conn = null;
  317. PreparedStatement pstm = null;
  318. ResultSet rs = null;
  319. StringBuilder sql = new StringBuilder();
  320. Object[] arg1 = new Object[dataMap.size()];
  321. Object[] arg2 = new Object[condition.size()];
  322. sql.append("update " + tableName + " set ");
  323. int i = 0;
  324. for (String aName : dataMap.keySet()) {
  325. if (i != dataMap.size() - 1) {
  326. sql.append("`" + aName + "` = ? ,");
  327. } else {
  328. sql.append("`" + aName + "` = ? where ");
  329. }
  330. arg1[i] = dataMap.get(aName);
  331. i++;
  332. }
  333. int j = 0;
  334. for (String cName : condition.keySet()) {
  335. if (j != condition.size() - 1) {
  336. sql.append("`" + cName + "` = ? ,");
  337. } else {
  338. sql.append("`" + cName + "` = ?");
  339. }
  340. arg2[j] = condition.get(cName);
  341. j++;
  342. }
  343. Object[] args = ArrayUtils.addAll(arg1, arg2);
  344. int re = 0;
  345. try {
  346. conn = dataSource.getConnection();
  347. pstm = conn.prepareStatement(sql.toString());
  348. for (int k = 0; k < args.length; k++) {
  349. pstm.setObject(k + 1, args[k]);
  350. }
  351. re = pstm.executeUpdate();
  352. long t2 = System.currentTimeMillis();
  353. log.info("MysqlUtil.update>>执行SQL: {}, 耗时: {}ms", sql.toString(), t2 - t1);
  354. log.info("MysqlUtil.update>>传入的参数值arg=>{}", Arrays.toString(args));
  355. if (re != 0) {
  356. log.info("MysqlUtil.update successfully !");
  357. return true;
  358. }
  359. } catch (Exception e) {
  360. log.error("MysqlUtil.update>>执行SQL: {}", sql);
  361. log.error("MysqlUtil.update>>传入的参数值arg=>{}", Arrays.toString(args));
  362. log.error("MysqlUtil.update log error!", e);
  363. } finally {
  364. close(rs, pstm, conn);
  365. }
  366. return re == 0 ? false : true;
  367. }
  368. /**
  369. * 依据condition删除数据
  370. *
  371. * @param condition Map<String, Object>形式,可以包含多条key value
  372. * @param tableName
  373. * @return true or false
  374. */
  375. public static boolean delete(Map<String, Object> condition, String tableName) {
  376. log.info("{}.{} Welcome to your arrival!", Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getMethodName());
  377. if (tableName == null || tableName.length() == 0) {
  378. log.error("MysqlUtil.delete Parameter[tableName] is empty ! Return!");
  379. return false;
  380. }
  381. if (condition == null || condition.size() == 0) {
  382. log.error("MysqlUtil.delete Parameter[condition] is empty ! Return !");
  383. return false;
  384. }
  385. long t1 = System.currentTimeMillis();
  386. Connection conn = null;
  387. PreparedStatement pstm = null;
  388. ResultSet rs = null;
  389. StringBuilder sql = new StringBuilder();
  390. Object[] args = new Object[condition.size()];
  391. sql.append("delete from " + tableName + " where ");
  392. int i = 0;
  393. for (String cName : condition.keySet()) {
  394. if (i != condition.size() - 1) {
  395. sql.append("`" + cName + "` = ? ,");
  396. } else {
  397. sql.append("`" + cName + "` = ?");
  398. }
  399. args[i] = condition.get(cName);
  400. i++;
  401. }
  402. int re = 0;
  403. try {
  404. conn = dataSource.getConnection();
  405. pstm = conn.prepareStatement(sql.toString());
  406. for (int k = 0; k < args.length; k++) {
  407. pstm.setObject(k + 1, args[k]);
  408. }
  409. re = p
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/1006260
推荐阅读
相关标签
  

闽ICP备14008679号