JdbcUtils.java 15 KB

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