JdbcUtils.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. package com.mes.util;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.sql.PreparedStatement;
  7. import java.sql.ResultSet;
  8. import java.sql.SQLException;
  9. import java.sql.Statement;
  10. import java.util.ArrayList;
  11. import java.util.LinkedHashSet;
  12. import java.util.List;
  13. import java.util.Set;
  14. public class JdbcUtils {
  15. public static final Logger log = LoggerFactory.getLogger(JdbcUtils.class);
  16. //通过上面的工具就可以获取到properties文件中的键值从而可以加载驱动 获取链接 从而 可以增删改查
  17. public static Connection conn = null;
  18. public static String Drivde="org.sqlite.JDBC";
  19. public static String DATABASE_URL="jdbc:sqlite:mes_db.db";
  20. public static Connection getConn(){
  21. try {
  22. Class.forName(Drivde);// 加载驱动,连接sqlite的jdbc
  23. conn = DriverManager.getConnection(DATABASE_URL);//连接数据库zhou.db,不存在则创建
  24. System.out.println("连接到SQLite数据库成功!");
  25. create_bw_record();//初始化结构表
  26. //create_measure_data();//初始化测试数据表
  27. } catch (Exception e) {
  28. // TODO Auto-generated catch block
  29. close();//关闭数据库连接
  30. e.printStackTrace();
  31. }
  32. return conn;
  33. }
  34. public static void openConnection() {
  35. try {
  36. Class.forName(Drivde);// 加载驱动,连接sqlite的jdbc
  37. conn = DriverManager.getConnection(DATABASE_URL);
  38. } catch (ClassNotFoundException e) {
  39. e.printStackTrace();
  40. } catch (SQLException e) {
  41. e.printStackTrace();
  42. // 如果连接失败,尝试重连
  43. reconnect();
  44. }
  45. }
  46. private static void reconnect() {
  47. try {
  48. // 关闭旧连接
  49. if (conn != null && !conn.isClosed()) {
  50. conn.close();
  51. }
  52. // 重新建立连接
  53. conn = DriverManager.getConnection(DATABASE_URL);
  54. } catch (SQLException e) {
  55. e.printStackTrace();
  56. // 如果重连失败,可以进一步处理异常,比如记录日志、通知管理员等
  57. }
  58. }
  59. public static void create_bw_record() throws SQLException {
  60. Statement statement=conn.createStatement(); //创建连接对象,是Java的一个操作数据库的重要接口
  61. //设备结构数据库
  62. String sqlEquipment = "CREATE TABLE if not exists bw_record("
  63. + "id INTEGER PRIMARY KEY AUTOINCREMENT,gw VARCHAR(20),gy VARCHAR(20),message_type VARCHAR(20),sn VARCHAR(48),bw VARCHAR(1000),record_time DATETIME,"
  64. + "info_01 VARCHAR(200),info_02 VARCHAR(200),info_03 VARCHAR(200))";
  65. // statement.executeUpdate("drop table if exists bw_record");//判断是否有表tables的存在。有则删除
  66. statement.executeUpdate(sqlEquipment);
  67. // 创建 提交记录表
  68. String submitRecord = "CREATE TABLE if not exists submit_record(\n" +
  69. " id INTEGER PRIMARY KEY AUTOINCREMENT, -- 自增ID\n" +
  70. " oprno VARCHAR(20), -- 工位号 \n" +
  71. " sn VARCHAR(48), -- 二维码\n" +
  72. " bw VARCHAR(1000), -- 报文 \n" +
  73. " record_time DATETIME, -- 记录时间\n" +
  74. " state CHAR(1) -- 状态(0 ->未提交, 1 ->已提交)\n" +
  75. ")";
  76. statement.executeUpdate(submitRecord);
  77. String opIpConfig = "CREATE TABLE if not exists op_ip_config(\n" +
  78. " op VARCHAR(20) PRIMARY KEY,\n" +
  79. " opname VARCHAR(100),\n" +
  80. " ip VARCHAR(50)\n" +
  81. ")";
  82. statement.executeUpdate(opIpConfig);
  83. String rivetRecord = "CREATE TABLE if not exists rivet_record(\n" +
  84. " id INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
  85. " oprno VARCHAR(20),\n" +
  86. " line_sn VARCHAR(20),\n" +
  87. " sn VARCHAR(48),\n" +
  88. " point_no INTEGER,\n" +
  89. " result VARCHAR(4),\n" +
  90. " stroke REAL,\n" +
  91. " pressure REAL,\n" +
  92. " hold_time INTEGER,\n" +
  93. " record_time DATETIME,\n" +
  94. " uploaded CHAR(1) DEFAULT '0'\n" +
  95. ")";
  96. statement.executeUpdate(rivetRecord);
  97. statement.close();
  98. }
  99. public static String getServerIpByOp(String op) {
  100. try {
  101. if (op == null || op.trim().isEmpty()) {
  102. return null;
  103. }
  104. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  105. JdbcUtils.openConnection();
  106. }
  107. String sql = "SELECT ip FROM op_ip_config WHERE op = ?";
  108. try (PreparedStatement ps = conn.prepareStatement(sql)) {
  109. ps.setString(1, op.trim());
  110. try (ResultSet rs = ps.executeQuery()) {
  111. if (rs.next()) {
  112. String ip = rs.getString("ip");
  113. return ip == null ? null : ip.trim();
  114. }
  115. }
  116. }
  117. } catch (Exception e) {
  118. log.info("查询op_ip_config失败: {}", e.getMessage());
  119. }
  120. return null;
  121. }
  122. public static String getOpNameByOp(String op) {
  123. try {
  124. if (op == null || op.trim().isEmpty()) {
  125. return null;
  126. }
  127. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  128. JdbcUtils.openConnection();
  129. }
  130. String sql = "SELECT opname FROM op_ip_config WHERE op = ?";
  131. try (PreparedStatement ps = conn.prepareStatement(sql)) {
  132. ps.setString(1, op.trim());
  133. try (ResultSet rs = ps.executeQuery()) {
  134. if (rs.next()) {
  135. String opname = rs.getString("opname");
  136. return opname == null ? null : opname.trim();
  137. }
  138. }
  139. }
  140. } catch (Exception e) {
  141. log.info("查询op_ip_config.opname失败: {}", e.getMessage());
  142. }
  143. return null;
  144. }
  145. public static boolean upsertOpIpConfig(String op, String opname, String ip) {
  146. boolean ret = false;
  147. try {
  148. if (op == null || op.trim().isEmpty() || ip == null || ip.trim().isEmpty()) {
  149. return false;
  150. }
  151. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  152. JdbcUtils.openConnection();
  153. }
  154. String sql = "INSERT INTO op_ip_config(op, opname, ip) VALUES(?, ?, ?) " +
  155. "ON CONFLICT(op) DO UPDATE SET opname=excluded.opname, ip=excluded.ip";
  156. try (PreparedStatement ps = conn.prepareStatement(sql)) {
  157. ps.setString(1, op.trim());
  158. ps.setString(2, opname == null ? "" : opname.trim());
  159. ps.setString(3, ip.trim());
  160. ps.executeUpdate();
  161. }
  162. ret = true;
  163. } catch (Exception e) {
  164. ret = false;
  165. log.info("保存op_ip_config失败: {}", e.getMessage());
  166. }
  167. return ret;
  168. }
  169. public static boolean clearOpIpConfig() {
  170. try {
  171. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  172. JdbcUtils.openConnection();
  173. }
  174. String sql = "DELETE FROM op_ip_config";
  175. try (PreparedStatement ps = conn.prepareStatement(sql)) {
  176. ps.executeUpdate();
  177. }
  178. return true;
  179. } catch (Exception e) {
  180. log.info("清除op_ip_config失败: {}", e.getMessage());
  181. return false;
  182. }
  183. }
  184. public static String[] getAnyOpIpConfig() {
  185. try {
  186. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  187. JdbcUtils.openConnection();
  188. }
  189. String sql = "SELECT op, opname, ip FROM op_ip_config ORDER BY rowid DESC LIMIT 1";
  190. try (PreparedStatement ps = conn.prepareStatement(sql);
  191. ResultSet rs = ps.executeQuery()) {
  192. if (rs.next()) {
  193. String op = rs.getString("op");
  194. String opname = rs.getString("opname");
  195. String ip = rs.getString("ip");
  196. return new String[]{
  197. op == null ? "" : op.trim(),
  198. opname == null ? "" : opname.trim(),
  199. ip == null ? "" : ip.trim()
  200. };
  201. }
  202. }
  203. } catch (Exception e) {
  204. log.info("查询op_ip_config任意配置失败: {}", e.getMessage());
  205. }
  206. return null;
  207. }
  208. //插入数据
  209. public static boolean insertData(String gw, String gy, String bw, String message_type, String sn) {
  210. boolean ret = false;
  211. String record_time = DateLocalUtils.getCurrentTime();
  212. try {
  213. // 确保连接已经打开
  214. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  215. JdbcUtils.openConnection();
  216. }
  217. //创建连接对象,是Java的一个操作数据库的重要接口
  218. Statement statement=conn.createStatement();
  219. statement.executeUpdate("INSERT INTO bw_record (gw,gy,bw,record_time,message_type,sn) VALUES"
  220. + " ('"+gw+"', '"+gy+"', '"+bw+"', '"+record_time+"','"+message_type+"','"+sn+"')");//向数据库中插入数据
  221. statement.close();
  222. ret = true;
  223. } catch (SQLException e) {
  224. // TODO Auto-generated catch block
  225. //e.printStackTrace();
  226. ret = false;
  227. }
  228. return ret;
  229. }
  230. // 向 submit_record表 插入提交记录数据
  231. public static boolean insertSubmitRecord(String oprno, String sn, String bw){
  232. boolean ret = false;
  233. String record_time = DateLocalUtils.getCurrentTime();
  234. try {
  235. // 确保连接已经打开
  236. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  237. JdbcUtils.openConnection();
  238. }
  239. Statement statement=conn.createStatement();
  240. String insertSQL = "INSERT INTO submit_record (oprno, sn, bw, record_time, state)" +
  241. "VALUES('" + oprno + "', '" + sn + "', '" + bw + "', '" + record_time + "', '0')";
  242. statement.executeUpdate(insertSQL);
  243. statement.close();
  244. ret = true;
  245. log.info("向submit_record表插入数据成功: {}", insertSQL);
  246. } catch (SQLException e) {
  247. ret = false;
  248. log.info("向submit_record表插入数据失败");
  249. }
  250. return ret;
  251. }
  252. public static boolean insertRivetRecord(String oprno, String lineSn, String sn, int pointNo,
  253. String result, float stroke, float pressure, int holdTime) {
  254. String recordTime = DateLocalUtils.getCurrentTime();
  255. try {
  256. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  257. JdbcUtils.openConnection();
  258. }
  259. String sql = "INSERT INTO rivet_record (oprno, line_sn, sn, point_no, result, stroke, pressure, hold_time, record_time, uploaded) " +
  260. "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, '0')";
  261. try (PreparedStatement ps = conn.prepareStatement(sql)) {
  262. ps.setString(1, oprno);
  263. ps.setString(2, lineSn);
  264. ps.setString(3, sn);
  265. ps.setInt(4, pointNo);
  266. ps.setString(5, result);
  267. ps.setFloat(6, stroke);
  268. ps.setFloat(7, pressure);
  269. ps.setInt(8, holdTime);
  270. ps.setString(9, recordTime);
  271. ps.executeUpdate();
  272. }
  273. log.info("铆接数据已保存: sn={}, point={}, result={}", sn, pointNo, result);
  274. return true;
  275. } catch (SQLException e) {
  276. log.info("保存铆接数据失败: {}", e.getMessage());
  277. return false;
  278. }
  279. }
  280. public static boolean markRivetRecordsUploaded(String sn) {
  281. try {
  282. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  283. JdbcUtils.openConnection();
  284. }
  285. String sql = "UPDATE rivet_record SET uploaded = '1' WHERE sn = ? AND uploaded = '0'";
  286. try (PreparedStatement ps = conn.prepareStatement(sql)) {
  287. ps.setString(1, sn);
  288. ps.executeUpdate();
  289. }
  290. return true;
  291. } catch (SQLException e) {
  292. log.info("更新铆接上传状态失败: sn={}, {}", sn, e.getMessage());
  293. return false;
  294. }
  295. }
  296. public static class RivetRecordItem {
  297. public String sn;
  298. public String oprno;
  299. public String lineSn;
  300. public int pointNo;
  301. public String result;
  302. public float stroke;
  303. public float pressure;
  304. public int holdTime;
  305. }
  306. public static List<String> getPendingRivetSnList() {
  307. List<String> list = new ArrayList<>();
  308. try {
  309. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  310. JdbcUtils.openConnection();
  311. }
  312. String sql = "SELECT DISTINCT sn FROM rivet_record WHERE uploaded = '0' ORDER BY sn";
  313. try (PreparedStatement ps = conn.prepareStatement(sql);
  314. ResultSet rs = ps.executeQuery()) {
  315. Set<String> seen = new LinkedHashSet<>();
  316. while (rs.next()) {
  317. seen.add(rs.getString("sn"));
  318. }
  319. list.addAll(seen);
  320. }
  321. } catch (SQLException e) {
  322. log.info("查询待上传工件码失败: {}", e.getMessage());
  323. }
  324. return list;
  325. }
  326. public static List<RivetRecordItem> getRivetRecordsBySn(String sn) {
  327. List<RivetRecordItem> list = new ArrayList<>();
  328. try {
  329. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  330. JdbcUtils.openConnection();
  331. }
  332. String sql = "SELECT sn, oprno, line_sn, point_no, result, stroke, pressure, hold_time " +
  333. "FROM rivet_record WHERE sn = ? AND uploaded = '0' ORDER BY point_no ASC";
  334. try (PreparedStatement ps = conn.prepareStatement(sql)) {
  335. ps.setString(1, sn);
  336. try (ResultSet rs = ps.executeQuery()) {
  337. while (rs.next()) {
  338. RivetRecordItem item = new RivetRecordItem();
  339. item.sn = rs.getString("sn");
  340. item.oprno = rs.getString("oprno");
  341. item.lineSn = rs.getString("line_sn");
  342. item.pointNo = rs.getInt("point_no");
  343. item.result = rs.getString("result");
  344. item.stroke = rs.getFloat("stroke");
  345. item.pressure = rs.getFloat("pressure");
  346. item.holdTime = rs.getInt("hold_time");
  347. list.add(item);
  348. }
  349. }
  350. }
  351. } catch (SQLException e) {
  352. log.info("查询铆接记录失败: sn={}, {}", sn, e.getMessage());
  353. }
  354. return list;
  355. }
  356. public static void deleteRivetRecordsBySn(String sn) {
  357. try {
  358. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  359. JdbcUtils.openConnection();
  360. }
  361. String sql = "DELETE FROM rivet_record WHERE sn = ?";
  362. try (PreparedStatement ps = conn.prepareStatement(sql)) {
  363. ps.setString(1, sn);
  364. ps.executeUpdate();
  365. }
  366. } catch (SQLException e) {
  367. log.info("删除铆接记录失败: {}", e.getMessage());
  368. }
  369. }
  370. public static void close(){
  371. try {
  372. if(conn!=null) {
  373. conn.close();
  374. }
  375. } catch (SQLException e) {
  376. e.printStackTrace();
  377. }
  378. }
  379. }