JdbcUtils.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. package com.mes.util;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import java.sql.*;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. public class JdbcUtils {
  8. public static final Logger log = LoggerFactory.getLogger(JdbcUtils.class);
  9. //通过上面的工具就可以获取到properties文件中的键值从而可以加载驱动 获取链接 从而 可以增删改查
  10. public static Connection conn = null;
  11. public static String Drivde="org.sqlite.JDBC";
  12. public static String DATABASE_URL="jdbc:sqlite:mes_db.db";
  13. public static Connection getConn(){
  14. try {
  15. Class.forName(Drivde);// 加载驱动,连接sqlite的jdbc
  16. conn = DriverManager.getConnection("jdbc:sqlite:mes_db.db");//连接数据库zhou.db,不存在则创建
  17. System.out.println("连接到SQLite数据库成功!");
  18. create_bw_record();//初始化结构表
  19. create_fsw_data();
  20. } catch (Exception e) {
  21. // TODO Auto-generated catch block
  22. close();//关闭数据库连接
  23. e.printStackTrace();
  24. }
  25. return conn;
  26. }
  27. public static void openConnection() {
  28. try {
  29. Class.forName(Drivde);// 加载驱动,连接sqlite的jdbc
  30. conn = DriverManager.getConnection(DATABASE_URL);
  31. create_fsw_data();
  32. } catch (ClassNotFoundException e) {
  33. e.printStackTrace();
  34. } catch (SQLException e) {
  35. e.printStackTrace();
  36. reconnect();
  37. }
  38. }
  39. private static void reconnect() {
  40. try {
  41. // 关闭旧连接
  42. if (conn != null && !conn.isClosed()) {
  43. conn.close();
  44. }
  45. // 重新建立连接
  46. conn = DriverManager.getConnection(DATABASE_URL);
  47. create_fsw_data();
  48. } catch (SQLException e) {
  49. e.printStackTrace();
  50. // 如果重连失败,可以进一步处理异常,比如记录日志、通知管理员等
  51. }
  52. }
  53. public static void create_bw_record() throws SQLException {
  54. Statement statement=conn.createStatement(); //创建连接对象,是Java的一个操作数据库的重要接口
  55. //设备结构数据库
  56. String sqlEquipment = "CREATE TABLE if not exists bw_record("
  57. + "id INTEGER PRIMARY KEY AUTOINCREMENT,gw VARCHAR(20),gy VARCHAR(20),message_type VARCHAR(20),sn VARCHAR(48),bw VARCHAR(1000),record_time DATETIME,"
  58. + "info_01 VARCHAR(200),info_02 VARCHAR(200),info_03 VARCHAR(200))";
  59. // statement.executeUpdate("drop table if exists bw_record");//判断是否有表tables的存在。有则删除
  60. statement.executeUpdate(sqlEquipment);
  61. // 创建 提交记录表
  62. String submitRecord = "CREATE TABLE if not exists submit_record(\n" +
  63. " id INTEGER PRIMARY KEY AUTOINCREMENT, -- 自增ID\n" +
  64. " oprno VARCHAR(20), -- 工位号 \n" +
  65. " sn VARCHAR(48), -- 二维码\n" +
  66. " bw VARCHAR(1000), -- 报文 \n" +
  67. " record_time DATETIME, -- 记录时间\n" +
  68. " state CHAR(1) -- 状态(0 ->未提交, 1 ->已提交)\n" +
  69. ")";
  70. statement.executeUpdate(submitRecord);
  71. //新增表
  72. String clientConfig = "CREATE TABLE if not exists client_config("
  73. + "config_key VARCHAR(100) PRIMARY KEY,"
  74. + "config_value VARCHAR(500),"
  75. + "update_time DATETIME"
  76. + ")";
  77. statement.executeUpdate(clientConfig);
  78. statement.close();
  79. }
  80. //新增方法
  81. public static void saveClientConfig(String key, String value) {
  82. try {
  83. if (conn == null || conn.isClosed()) {
  84. openConnection();
  85. }
  86. String sql = "INSERT INTO client_config (config_key, config_value, update_time) VALUES (?, ?, ?) "
  87. + "ON CONFLICT(config_key) DO UPDATE SET config_value = excluded.config_value, update_time = excluded.update_time";
  88. PreparedStatement ps = conn.prepareStatement(sql);
  89. ps.setString(1, key);
  90. ps.setString(2, value);
  91. ps.setString(3, DateLocalUtils.getCurrentTime());
  92. ps.executeUpdate();
  93. ps.close();
  94. log.info("保存本地配置: {}={}", key, value);
  95. } catch (SQLException e) {
  96. log.info("保存本地配置失败: {}", e.getMessage());
  97. }
  98. }
  99. //新增方法
  100. public static String getClientConfig(String key, String defaultValue) {
  101. try {
  102. if (conn == null || conn.isClosed()) {
  103. openConnection();
  104. }
  105. String sql = "SELECT config_value FROM client_config WHERE config_key = ?";
  106. PreparedStatement ps = conn.prepareStatement(sql);
  107. ps.setString(1, key);
  108. ResultSet rs = ps.executeQuery();
  109. if (rs.next()) {
  110. String value = rs.getString("config_value");
  111. rs.close();
  112. ps.close();
  113. return value;
  114. }
  115. rs.close();
  116. ps.close();
  117. } catch (SQLException e) {
  118. log.info("读取本地配置失败: {}", e.getMessage());
  119. }
  120. return defaultValue;
  121. }
  122. //新增方法
  123. public static String getProductTypeConfigKey(String gw) {
  124. return "product_type_" + gw;
  125. }
  126. public static void create_fsw_data() throws SQLException {
  127. Statement statement = conn.createStatement();
  128. String sql = "CREATE TABLE if not exists fsw_params("
  129. + "id INTEGER PRIMARY KEY AUTOINCREMENT,"
  130. + "oprno VARCHAR(20),"
  131. + "line_sn VARCHAR(20),"
  132. + "sn VARCHAR(100),"
  133. + "spindle_speed VARCHAR(50),"
  134. + "feed_rate VARCHAR(50),"
  135. + "pressure VARCHAR(50),"
  136. + "ucode VARCHAR(50),"
  137. + "record_time DATETIME,"
  138. + "sync INT DEFAULT 0"
  139. + ")";
  140. statement.executeUpdate(sql);
  141. statement.close();
  142. }
  143. public static boolean insertFswParam(String oprno, String lineSn, String sn,
  144. String spindleSpeed, String feedRate, String pressure, String ucode) {
  145. String recordTime = DateLocalUtils.getCurrentTime();
  146. try {
  147. if (conn == null || conn.isClosed()) {
  148. openConnection();
  149. }
  150. Statement statement = conn.createStatement();
  151. statement.executeUpdate("INSERT INTO fsw_params (oprno,line_sn,sn,spindle_speed,feed_rate,pressure,ucode,record_time,sync) VALUES ("
  152. + "'" + sqlEscape(oprno) + "',"
  153. + "'" + sqlEscape(lineSn) + "',"
  154. + "'" + sqlEscape(sn) + "',"
  155. + "'" + sqlEscape(spindleSpeed) + "',"
  156. + "'" + sqlEscape(feedRate) + "',"
  157. + "'" + sqlEscape(pressure) + "',"
  158. + "'" + sqlEscape(ucode) + "',"
  159. + "'" + recordTime + "',"
  160. + "0)");
  161. statement.close();
  162. return true;
  163. } catch (SQLException e) {
  164. log.info("向fsw_params表插入数据失败: {}", e.getMessage());
  165. return false;
  166. }
  167. }
  168. public static List<FswParamReq> getFswParams() {
  169. List<FswParamReq> list = new ArrayList<>();
  170. String sql = "select id,oprno,line_sn,sn,spindle_speed,feed_rate,pressure,ucode,sync from fsw_params where sync = 0 order by id asc limit 100";
  171. try {
  172. if (conn == null || conn.isClosed()) {
  173. openConnection();
  174. }
  175. Statement stmt = conn.createStatement();
  176. ResultSet ret = stmt.executeQuery(sql);
  177. while (ret.next()) {
  178. FswParamReq req = new FswParamReq();
  179. req.setId(ret.getInt(1));
  180. req.setOprno(ret.getString(2));
  181. req.setLineSn(ret.getString(3));
  182. req.setSn(ret.getString(4));
  183. req.setSpindleSpeed(ret.getString(5));
  184. req.setFeedRate(ret.getString(6));
  185. req.setPressure(ret.getString(7));
  186. req.setUcode(ret.getString(8));
  187. req.setSync(ret.getInt(9));
  188. list.add(req);
  189. }
  190. ret.close();
  191. stmt.close();
  192. } catch (SQLException e) {
  193. log.info("读取fsw_params失败: {}", e.getMessage());
  194. }
  195. return list;
  196. }
  197. public static void updateFswSync(Integer id, Integer sync) throws SQLException {
  198. if (conn == null || conn.isClosed()) {
  199. openConnection();
  200. }
  201. Statement statement = conn.createStatement();
  202. statement.executeUpdate("update fsw_params set sync = " + sync + " where id = " + id);
  203. statement.close();
  204. }
  205. private static String sqlEscape(String value) {
  206. if (value == null) {
  207. return "";
  208. }
  209. return value.replace("'", "''");
  210. }
  211. //插入数据
  212. public static boolean insertData(String gw, String gy, String bw, String message_type, String sn) {
  213. boolean ret = false;
  214. String record_time = DateLocalUtils.getCurrentTime();
  215. try {
  216. // 确保连接已经打开
  217. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  218. JdbcUtils.openConnection();
  219. }
  220. //创建连接对象,是Java的一个操作数据库的重要接口
  221. Statement statement=conn.createStatement();
  222. statement.executeUpdate("INSERT INTO bw_record (gw,gy,bw,record_time,message_type,sn) VALUES"
  223. + " ('"+gw+"', '"+gy+"', '"+bw+"', '"+record_time+"','"+message_type+"','"+sn+"')");//向数据库中插入数据
  224. statement.close();
  225. ret = true;
  226. } catch (SQLException e) {
  227. // TODO Auto-generated catch block
  228. //e.printStackTrace();
  229. ret = false;
  230. }
  231. return ret;
  232. }
  233. // 向 submit_record表 插入提交记录数据
  234. public static boolean insertSubmitRecord(String oprno, String sn, String bw){
  235. boolean ret = false;
  236. String record_time = DateLocalUtils.getCurrentTime();
  237. try {
  238. // 确保连接已经打开
  239. if (JdbcUtils.conn == null || JdbcUtils.conn.isClosed()) {
  240. JdbcUtils.openConnection();
  241. }
  242. Statement statement=conn.createStatement();
  243. String insertSQL = "INSERT INTO submit_record (oprno, sn, bw, record_time, state)" +
  244. "VALUES('" + oprno + "', '" + sn + "', '" + bw + "', '" + record_time + "', '0')";
  245. statement.executeUpdate(insertSQL);
  246. statement.close();
  247. ret = true;
  248. log.info("向submit_record表插入数据成功: {}", insertSQL);
  249. } catch (SQLException e) {
  250. ret = false;
  251. log.info("向submit_record表插入数据失败");
  252. }
  253. return ret;
  254. }
  255. public static void close(){
  256. try {
  257. if(conn!=null) {
  258. conn.close();
  259. }
  260. } catch (SQLException e) {
  261. e.printStackTrace();
  262. }
  263. }
  264. }