JdbcUtils.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. package com.mes.util;
  2. import com.alibaba.fastjson2.JSON;
  3. import com.alibaba.fastjson2.JSONObject;
  4. import com.mes.ui.CacheData;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import java.sql.*;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. public class JdbcUtils {
  11. public static final Logger log = LoggerFactory.getLogger(JdbcUtils.class);
  12. //通过上面的工具就可以获取到properties文件中的键值从而可以加载驱动 获取链接 从而 可以增删改查
  13. public static Connection conn = null;
  14. public static String Drivde="org.sqlite.JDBC";
  15. public static String DATABASE_URL="jdbc:sqlite:mes_db.db";
  16. // 全局复用一个连接,已打开则直接返回,避免每次新建导致连接泄漏
  17. public static synchronized Connection getConn(){
  18. try {
  19. if(conn != null && !conn.isClosed()){
  20. return conn;
  21. }
  22. Class.forName(Drivde);// 加载驱动,连接sqlite的jdbc
  23. conn = DriverManager.getConnection(DATABASE_URL);//连接数据库zhou.db,不存在则创建
  24. create_bw_record();//初始化结构表
  25. //create_measure_data();//初始化测试数据表
  26. } catch (Exception e) {
  27. // TODO Auto-generated catch block
  28. close();//关闭数据库连接
  29. e.printStackTrace();
  30. }
  31. return conn;
  32. }
  33. public static void openConnection() {
  34. try {
  35. Class.forName(Drivde);// 加载驱动,连接sqlite的jdbc
  36. conn = DriverManager.getConnection(DATABASE_URL);
  37. } catch (ClassNotFoundException e) {
  38. e.printStackTrace();
  39. } catch (SQLException e) {
  40. e.printStackTrace();
  41. // 如果连接失败,尝试重连
  42. reconnect();
  43. }
  44. }
  45. private static void reconnect() {
  46. try {
  47. // 关闭旧连接
  48. if (conn != null && !conn.isClosed()) {
  49. conn.close();
  50. }
  51. // 重新建立连接
  52. conn = DriverManager.getConnection(DATABASE_URL);
  53. } catch (SQLException e) {
  54. e.printStackTrace();
  55. // 如果重连失败,可以进一步处理异常,比如记录日志、通知管理员等
  56. }
  57. }
  58. public static void create_bw_record() throws SQLException {
  59. Statement statement=conn.createStatement(); //创建连接对象,是Java的一个操作数据库的重要接口
  60. //设备结构数据库
  61. String sqlEquipment = "CREATE TABLE if not exists bw_record("
  62. + "id INTEGER PRIMARY KEY AUTOINCREMENT,gw VARCHAR(20),gy VARCHAR(20),message_type VARCHAR(20),sn VARCHAR(48),bw VARCHAR(1000),record_time DATETIME,"
  63. + "info_01 VARCHAR(200),info_02 VARCHAR(200),info_03 VARCHAR(200))";
  64. // statement.executeUpdate("drop table if exists bw_record");//判断是否有表tables的存在。有则删除
  65. statement.executeUpdate(sqlEquipment);
  66. // 创建 提交记录表
  67. String submitRecord = "CREATE TABLE if not exists submit_record(\n" +
  68. " id INTEGER PRIMARY KEY AUTOINCREMENT, -- 自增ID\n" +
  69. " oprno VARCHAR(20), -- 工位号 \n" +
  70. " sn VARCHAR(48), -- 二维码\n" +
  71. " bw VARCHAR(1000), -- 报文 \n" +
  72. " record_time DATETIME, -- 记录时间\n" +
  73. " state CHAR(1) -- 状态(0 ->未提交, 1 ->已提交)\n" +
  74. ")";
  75. statement.executeUpdate(submitRecord);
  76. String sqlEquipment2 = "CREATE TABLE if not exists bw_params("
  77. + "id INTEGER PRIMARY KEY AUTOINCREMENT,oprno VARCHAR(20),line_sn VARCHAR(20),"
  78. + "sn VARCHAR(50),content MEDIUMTEXT,create_time DATETIME,sync int(10) NULL DEFAULT 0"
  79. + ")";
  80. statement.executeUpdate(sqlEquipment2);
  81. // 创建 提交记录表
  82. String cache = "CREATE TABLE if not exists cache(\n" +
  83. " id INTEGER PRIMARY KEY AUTOINCREMENT, -- 自增ID\n" +
  84. " sn VARCHAR(20), -- 唯一标识 \n" +
  85. " content VARCHAR(3000), -- 绑定内容\n" +
  86. " record_time DATETIME, -- 记录时间\n" +
  87. " UNIQUE (sn) -- 唯一索引\n" +
  88. ")";
  89. statement.executeUpdate(cache);
  90. statement.close();
  91. }
  92. public static synchronized CacheData getCache(String key) {
  93. String content = "";
  94. // 复用全局连接,不再关闭,避免关掉其他线程正在用的连接
  95. try (PreparedStatement ps = getConn().prepareStatement("select content from cache where sn = ? order by id asc limit 1")) {
  96. ps.setString(1, key);
  97. try (ResultSet ret = ps.executeQuery()) {
  98. if (ret.next()) {
  99. content = ret.getString(1);
  100. }
  101. }
  102. } catch (SQLException e1) {
  103. e1.printStackTrace();
  104. }
  105. if(content == null || content.trim().isEmpty()){
  106. return null;
  107. }
  108. content = CommonUtils.base64Decode(content);
  109. return JSON.parseObject(content,CacheData.class);
  110. }
  111. public static synchronized Boolean setCache(String key,String value) {
  112. if(value == null || value.trim().isEmpty()) {
  113. return false;
  114. }
  115. value = CommonUtils.base64Encode(value).trim();
  116. // sn 有唯一索引,存在则覆盖,不存在则新增,避免并发 insert 冲突
  117. try (PreparedStatement ps = getConn().prepareStatement("INSERT OR REPLACE INTO cache (sn,content,record_time) VALUES (?,?,?)")) {
  118. ps.setString(1, key);
  119. ps.setString(2, value);
  120. ps.setString(3, DateLocalUtils.getCurrentTime());
  121. ps.executeUpdate();
  122. }catch (Exception e) {
  123. e.printStackTrace();
  124. }
  125. return true;
  126. }
  127. //插入数据
  128. public static synchronized boolean insertData(String gw, String gy, String bw, String message_type, String sn) {
  129. boolean ret = false;
  130. String record_time = DateLocalUtils.getCurrentTime();
  131. if(getConn()==null) {
  132. ret = false;
  133. }else {
  134. try {
  135. //创建连接对象,是Java的一个操作数据库的重要接口
  136. Statement statement=conn.createStatement();
  137. statement.executeUpdate("INSERT INTO bw_record (gw,gy,bw,record_time,message_type,sn) VALUES"
  138. + " ('"+gw+"', '"+gy+"', '"+bw+"', '"+record_time+"','"+message_type+"','"+sn+"')");//向数据库中插入数据
  139. statement.close();
  140. ret = true;
  141. } catch (SQLException e) {
  142. // TODO Auto-generated catch block
  143. //e.printStackTrace();
  144. ret = false;
  145. }
  146. }
  147. return ret;
  148. }
  149. // 向 submit_record表 插入提交记录数据
  150. public static synchronized boolean insertSubmitRecord(String oprno, String sn, String bw){
  151. boolean ret = false;
  152. String record_time = DateLocalUtils.getCurrentTime();
  153. if(getConn()==null) {
  154. ret = false;
  155. }else {
  156. try {
  157. Statement statement=conn.createStatement();
  158. String insertSQL = "INSERT INTO submit_record (oprno, sn, bw, record_time, state)" +
  159. "VALUES('" + oprno + "', '" + sn + "', '" + bw + "', '" + record_time + "', '0')";
  160. statement.executeUpdate(insertSQL);
  161. statement.close();
  162. ret = true;
  163. log.info("向submit_record表插入数据成功: " + insertSQL);
  164. } catch (SQLException e) {
  165. ret = false;
  166. log.info("向submit_record表插入数据失败");
  167. }
  168. }
  169. return ret;
  170. }
  171. public static void create_measure_data() throws SQLException {
  172. Statement statement=conn.createStatement(); //创建连接对象,是Java的一个操作数据库的重要接口
  173. //statement.executeUpdate("drop table if exists measure_data");//判断是否有表tables的存在。有则删除
  174. //设备结构数据库
  175. String sqlEquipment = "CREATE TABLE if not exists measure_data("
  176. + "id INTEGER PRIMARY KEY AUTOINCREMENT,function_location VARCHAR(200),description VARCHAR(200),"
  177. + "data_item VARCHAR(100),measure_time DATETIME,data_type INT(3)," //data_type=1电阻校准数据,2电感校准数据,3绝缘电阻校准数据
  178. + "data_01 double(30),data_02 double(30),data_03 double(30),data_04 double(30),data_05 double(30),"
  179. + "data_06 double(30),data_07 double(30),data_08 double(30),data_09 double(30),data_10 double(30),"
  180. + "data_11 double(30),data_12 double(30),data_13 double(30),data_14 double(30),data_15 double(30),"
  181. + "data_16 double(30),data_17 double(30),data_18 double(30),data_19 double(30),data_20 double(30)"
  182. + ")";
  183. statement.executeUpdate(sqlEquipment);
  184. // statement.executeUpdate("INSERT INTO measure_data VALUES (1, '第一电厂-设备管理部-电机1', '第一电厂-设备管理部-电机1', '2022-03-22 15:16:18', '2022-03-22 15:16:18',1,"
  185. // + "0.05, 0.82, 3, 80, 130, 180, 402, 502, 809, 1103, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)");//向数据库中插入数据
  186. // ResultSet rSet=statement.executeQuery("select * from measure_data");//搜索数据库,将搜索的放入数据集ResultSet中
  187. // while (rSet.next()) { //遍历这个数据集
  188. // log.info("function_location:"+rSet.getString(2));//依次输出 也可以这样写 rSet.getString(“name”)
  189. // log.info("data_01:"+rSet.getString(4));
  190. // }
  191. // rSet.close();//关闭数据集
  192. statement.close();
  193. }
  194. public static synchronized void close(){
  195. log.info("SQLite数据库连接关闭!");
  196. try {
  197. if(conn!=null) {
  198. conn.close();
  199. }
  200. } catch (SQLException e) {
  201. e.printStackTrace();
  202. }
  203. }
  204. //设备结构数据库
  205. // String sqlEquipment = "CREATE TABLE if not exists tree_structure(id INTEGER PRIMARY KEY AUTOINCREMENT,function_location VARCHAR(200),description VARCHAR(200),sup_fl VARCHAR(200),level INT(3)," +
  206. // "isleaf INT(3))";
  207. // statement.executeUpdate("drop table if exists tree_structure");//判断是否有表tables的存在。有则删除
  208. // statement.executeUpdate(sqlEquipment);
  209. // statement.executeUpdate("INSERT INTO tree_structure VALUES (1, '第一电厂', '第一电厂', NULL, 1, 0)");//向数据库中插入数据
  210. // statement.executeUpdate("INSERT INTO tree_structure VALUES (2, '第一电厂-设备管理部', '第一电厂-设备管理部', '第一电厂', 2, 0)");//向数据库中插入数据
  211. // statement.executeUpdate("INSERT INTO tree_structure VALUES (3, '第一电厂-设备管理部-发电机组', '第一电厂-设备管理部-发电机组', '第一电厂-设备管理部', 3, 0)");//向数据库中插入数据
  212. // statement.executeUpdate("INSERT INTO tree_structure VALUES (4, '第一电厂-设备管理部-发电机组-电机1', '第一电厂-设备管理部-发电机组-电机1', '第一电厂-设备管理部-发电机组', 4, 1)");//向数据库中插入数据
  213. // statement.executeUpdate("INSERT INTO tree_structure VALUES (5, '第一电厂-设备管理部-发电机组-电机2', '第一电厂-设备管理部-发电机组-电机2', '第一电厂-设备管理部-发电机组', 4, 1)");//向数据库中插入数据
  214. // statement.executeUpdate("INSERT INTO tree_structure VALUES (6, '第二电厂', '第二电厂', NULL, 1, 0)");//向数据库中插入数据
  215. // statement.executeUpdate("INSERT INTO tree_structure VALUES (7, '第二电厂-设备管理部', '第二电厂-设备管理部', '第二电厂', 2, 0)");//向数据库中插入数据
  216. // statement.executeUpdate("INSERT INTO tree_structure VALUES (8, '第一电厂-设备管理部-发电机组-电机3', '第一电厂-设备管理部-发电机组-电机3', '第一电厂-设备管理部-发电机组', 4, 1)");//向数据库中插入数据
  217. // statement.executeUpdate("INSERT INTO tree_structure VALUES (10, '第一电厂-设备管理部-发电机组-电机4', '第一电厂-设备管理部-发电机组-电机4', '第一电厂-设备管理部-发电机组', 4, 1)");//向数据库中插入数据
  218. // statement.executeUpdate("INSERT INTO tree_structure VALUES (11, '第一电厂-设备管理部-发电机组-电机5', '第一电厂-设备管理部-发电机组-电机5', '第一电厂-设备管理部-发电机组', 4, 1)");//向数据库中插入数据
  219. // statement.executeUpdate("INSERT INTO tree_structure VALUES (12, '第一电厂-设备管理部-发电机组-电机8', '第一电厂-设备管理部-发电机组-电机8', '第一电厂-设备管理部-发电机组', 4, 1)");//向数据库中插入数据
  220. // statement.executeUpdate("INSERT INTO tree_structure VALUES (13, '第一电厂-设备管理部-发电机组-电机6', '第一电厂-设备管理部-发电机组-电机6', '第一电厂-设备管理部-发电机组', 4, 1)");//向数据库中插入数据
  221. // statement.executeUpdate("INSERT INTO tree_structure VALUES (14, '第一电厂-设备管理部-发电机组-电机7', '第一电厂-设备管理部-发电机组-电机7', '第一电厂-设备管理部-发电机组', 4, 1)");//向数据库中插入数据
  222. // statement.executeUpdate("INSERT INTO tree_structure VALUES (15, '第一电厂-设备管理部-发电机组-电机9', '第一电厂-设备管理部-发电机组-电机9', '第一电厂-设备管理部-发电机组', 4, 1)");//向数据库中插入数据
  223. // statement.executeUpdate("INSERT INTO tree_structure VALUES (16, '第一电厂-设备管理部-发电机组-电机10', '第一电厂-设备管理部-发电机组-电机10', '第一电厂-设备管理部-发电机组', 4, 1)");//向数据库中插入数据
  224. // ResultSet rSet=statement.executeQuery("select * from tree_structure");//搜索数据库,将搜索的放入数据集ResultSet中
  225. // /**
  226. // * 通过用户名到数据库中获取凭证密码
  227. // * @param userName
  228. // * @return
  229. // */
  230. // private static String getPasswordByUserName(String userName) {
  231. // //SQL语句
  232. // String sql = "select password from users where username = " +"'" + userName+"'";
  233. // Connection conn = JdbcUtils.getConn();
  234. // Statement stmt=null;
  235. // ResultSet ret = null;
  236. // String password=null;
  237. // try {
  238. // stmt = conn.createStatement();
  239. // //执行语句,得到结果集
  240. // ret = stmt.executeQuery(sql);
  241. // while (ret.next()) {
  242. // //这里只查询的密码
  243. // password = ret.getString(1);
  244. // }
  245. // ret.close();
  246. // conn.close();//关闭连接
  247. // } catch (SQLException e1) {
  248. // e1.printStackTrace();
  249. // }
  250. // return password;
  251. // }
  252. }