JdbcUtils.java 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. 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. public static Connection getConn(){
  17. try {
  18. Class.forName(Drivde);// 加载驱动,连接sqlite的jdbc
  19. conn = DriverManager.getConnection(DATABASE_URL);//连接数据库zhou.db,不存在则创建
  20. System.out.println("连接到SQLite数据库成功!");
  21. create_bw_record();//初始化结构表
  22. //create_measure_data();//初始化测试数据表
  23. } catch (Exception e) {
  24. // TODO Auto-generated catch block
  25. close();//关闭数据库连接
  26. e.printStackTrace();
  27. }
  28. return conn;
  29. }
  30. public static void openConnection() {
  31. try {
  32. Class.forName(Drivde);// 加载驱动,连接sqlite的jdbc
  33. conn = DriverManager.getConnection(DATABASE_URL);
  34. } catch (ClassNotFoundException e) {
  35. e.printStackTrace();
  36. } catch (SQLException e) {
  37. e.printStackTrace();
  38. // 如果连接失败,尝试重连
  39. reconnect();
  40. }
  41. }
  42. private static void reconnect() {
  43. try {
  44. // 关闭旧连接
  45. if (conn != null && !conn.isClosed()) {
  46. conn.close();
  47. }
  48. // 重新建立连接
  49. conn = DriverManager.getConnection(DATABASE_URL);
  50. } catch (SQLException e) {
  51. e.printStackTrace();
  52. // 如果重连失败,可以进一步处理异常,比如记录日志、通知管理员等
  53. }
  54. }
  55. public static void create_bw_record() throws SQLException {
  56. Statement statement=conn.createStatement(); //创建连接对象,是Java的一个操作数据库的重要接口
  57. //设备结构数据库
  58. String sqlEquipment = "CREATE TABLE if not exists bw_record("
  59. + "id INTEGER PRIMARY KEY AUTOINCREMENT,gw VARCHAR(20),gy VARCHAR(20),message_type VARCHAR(20),sn VARCHAR(48),bw VARCHAR(1000),record_time DATETIME,"
  60. + "info_01 VARCHAR(200),info_02 VARCHAR(200),info_03 VARCHAR(200))";
  61. // statement.executeUpdate("drop table if exists bw_record");//判断是否有表tables的存在。有则删除
  62. statement.executeUpdate(sqlEquipment);
  63. // 创建 提交记录表
  64. String submitRecord = "CREATE TABLE if not exists submit_record(\n" +
  65. " id INTEGER PRIMARY KEY AUTOINCREMENT, -- 自增ID\n" +
  66. " oprno VARCHAR(20), -- 工位号 \n" +
  67. " sn VARCHAR(48), -- 二维码\n" +
  68. " bw VARCHAR(1000), -- 报文 \n" +
  69. " record_time DATETIME, -- 记录时间\n" +
  70. " state CHAR(1) -- 状态(0 ->未提交, 1 ->已提交)\n" +
  71. ")";
  72. statement.executeUpdate(submitRecord);
  73. String opIpConfig = "CREATE TABLE if not exists op_ip_config(\n" +
  74. " op VARCHAR(20) PRIMARY KEY,\n" +
  75. " opname VARCHAR(100),\n" +
  76. " ip VARCHAR(50)\n" +
  77. ")";
  78. statement.executeUpdate(opIpConfig);
  79. statement.close();
  80. }
  81. public static String getServerIpByOp(String op) {
  82. try {
  83. if (op == null || op.trim().isEmpty()) {
  84. return null;
  85. }
  86. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  87. JdbcUtils.openConnection();
  88. }
  89. String sql = "SELECT ip FROM op_ip_config WHERE op = ?";
  90. try (PreparedStatement ps = conn.prepareStatement(sql)) {
  91. ps.setString(1, op.trim());
  92. try (ResultSet rs = ps.executeQuery()) {
  93. if (rs.next()) {
  94. String ip = rs.getString("ip");
  95. return ip == null ? null : ip.trim();
  96. }
  97. }
  98. }
  99. } catch (Exception e) {
  100. log.info("查询op_ip_config失败: {}", e.getMessage());
  101. }
  102. return null;
  103. }
  104. public static String getOpNameByOp(String op) {
  105. try {
  106. if (op == null || op.trim().isEmpty()) {
  107. return null;
  108. }
  109. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  110. JdbcUtils.openConnection();
  111. }
  112. String sql = "SELECT opname FROM op_ip_config WHERE op = ?";
  113. try (PreparedStatement ps = conn.prepareStatement(sql)) {
  114. ps.setString(1, op.trim());
  115. try (ResultSet rs = ps.executeQuery()) {
  116. if (rs.next()) {
  117. String opname = rs.getString("opname");
  118. return opname == null ? null : opname.trim();
  119. }
  120. }
  121. }
  122. } catch (Exception e) {
  123. log.info("查询op_ip_config.opname失败: {}", e.getMessage());
  124. }
  125. return null;
  126. }
  127. public static boolean upsertOpIpConfig(String op, String opname, String ip) {
  128. boolean ret = false;
  129. try {
  130. if (op == null || op.trim().isEmpty() || ip == null || ip.trim().isEmpty()) {
  131. return false;
  132. }
  133. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  134. JdbcUtils.openConnection();
  135. }
  136. String sql = "INSERT INTO op_ip_config(op, opname, ip) VALUES(?, ?, ?) " +
  137. "ON CONFLICT(op) DO UPDATE SET opname=excluded.opname, ip=excluded.ip";
  138. try (PreparedStatement ps = conn.prepareStatement(sql)) {
  139. ps.setString(1, op.trim());
  140. ps.setString(2, opname == null ? "" : opname.trim());
  141. ps.setString(3, ip.trim());
  142. ps.executeUpdate();
  143. }
  144. ret = true;
  145. } catch (Exception e) {
  146. ret = false;
  147. log.info("保存op_ip_config失败: {}", e.getMessage());
  148. }
  149. return ret;
  150. }
  151. public static boolean clearOpIpConfig() {
  152. try {
  153. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  154. JdbcUtils.openConnection();
  155. }
  156. String sql = "DELETE FROM op_ip_config";
  157. try (PreparedStatement ps = conn.prepareStatement(sql)) {
  158. ps.executeUpdate();
  159. }
  160. return true;
  161. } catch (Exception e) {
  162. log.info("清除op_ip_config失败: {}", e.getMessage());
  163. return false;
  164. }
  165. }
  166. public static String[] getAnyOpIpConfig() {
  167. try {
  168. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  169. JdbcUtils.openConnection();
  170. }
  171. String sql = "SELECT op, opname, ip FROM op_ip_config ORDER BY rowid DESC LIMIT 1";
  172. try (PreparedStatement ps = conn.prepareStatement(sql);
  173. ResultSet rs = ps.executeQuery()) {
  174. if (rs.next()) {
  175. String op = rs.getString("op");
  176. String opname = rs.getString("opname");
  177. String ip = rs.getString("ip");
  178. return new String[]{
  179. op == null ? "" : op.trim(),
  180. opname == null ? "" : opname.trim(),
  181. ip == null ? "" : ip.trim()
  182. };
  183. }
  184. }
  185. } catch (Exception e) {
  186. log.info("查询op_ip_config任意配置失败: {}", e.getMessage());
  187. }
  188. return null;
  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. try {
  195. // 确保连接已经打开
  196. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  197. JdbcUtils.openConnection();
  198. }
  199. //创建连接对象,是Java的一个操作数据库的重要接口
  200. Statement statement=conn.createStatement();
  201. statement.executeUpdate("INSERT INTO bw_record (gw,gy,bw,record_time,message_type,sn) VALUES"
  202. + " ('"+gw+"', '"+gy+"', '"+bw+"', '"+record_time+"','"+message_type+"','"+sn+"')");//向数据库中插入数据
  203. statement.close();
  204. ret = true;
  205. } catch (SQLException e) {
  206. // TODO Auto-generated catch block
  207. //e.printStackTrace();
  208. ret = false;
  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. try {
  217. // 确保连接已经打开
  218. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  219. JdbcUtils.openConnection();
  220. }
  221. Statement statement=conn.createStatement();
  222. String insertSQL = "INSERT INTO submit_record (oprno, sn, bw, record_time, state)" +
  223. "VALUES('" + oprno + "', '" + sn + "', '" + bw + "', '" + record_time + "', '0')";
  224. statement.executeUpdate(insertSQL);
  225. statement.close();
  226. ret = true;
  227. log.info("向submit_record表插入数据成功: {}", insertSQL);
  228. } catch (SQLException e) {
  229. ret = false;
  230. log.info("向submit_record表插入数据失败");
  231. }
  232. return ret;
  233. }
  234. public static void close(){
  235. try {
  236. if(conn!=null) {
  237. conn.close();
  238. }
  239. } catch (SQLException e) {
  240. e.printStackTrace();
  241. }
  242. }
  243. }