SQLHelper.cs 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.SqlClient;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Data;
  8. using System.IO;
  9. using HslCommunication.LogNet;
  10. using Org.BouncyCastle.Ocsp;
  11. using System.Windows.Forms;
  12. using SqlSugar;
  13. using MainForm.ClassFile.ProjectClass;
  14. using NPOI.SS.Formula.Functions;
  15. namespace MainForm
  16. {
  17. public class SQLHelper
  18. {
  19. public static string DBDir = GlobalContext.DBDir;
  20. //用于数据库日志记录
  21. private static ILogNet logNet = new LogNetDateTime(GlobalContext.SQLLogDir, GenerateMode.ByEveryDay);
  22. /// <summary>
  23. /// 使用锁防止多线程同时操作数据库表
  24. /// </summary>
  25. private static readonly object sqlLock = new object();
  26. public class ResponseMessage
  27. {
  28. public string text { get; set; }
  29. public bool result { get; set; }
  30. }
  31. /// <summary>
  32. /// SQL连接
  33. /// </summary>
  34. private static SqlConnection connection = null;
  35. public static string connString = "";
  36. public static void DBInitWork()
  37. {
  38. GlobalContext.User = "sa";
  39. GlobalContext.PassWord = "Bb123456";
  40. //以月为单位存
  41. string subDir = DateTime.Now.ToString("yyyyMM");
  42. string dataBaseName = "DB" + subDir;
  43. connString =
  44. @"server= " + GlobalContext.Server +
  45. ";database= " + dataBaseName +
  46. ";uid=" + GlobalContext.User +
  47. ";pwd=" + GlobalContext.PassWord;
  48. //判断路径是否存在,不存在则创建路径
  49. if (!Directory.Exists(DBDir + subDir)) Directory.CreateDirectory(DBDir + subDir);
  50. //创建数据库和表
  51. SQLHelper.CreateDataBase(DBDir, subDir, dataBaseName);
  52. //SQLHelper.CreateDataBase();
  53. }
  54. /// <summary>
  55. /// 查询
  56. /// </summary>
  57. /// <param name="SQLString"></param>
  58. /// <param name="cmdParms"></param>
  59. /// <returns></returns>
  60. /// <exception cref="Exception"></exception>
  61. public static DataSet Query(string SQLString, List<SqlParameter> cmdParms, string connectionString)
  62. {
  63. using (SqlConnection connection = new SqlConnection(connectionString))
  64. {
  65. SqlCommand cmd = new SqlCommand();
  66. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  67. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  68. {
  69. DataSet ds = new DataSet();
  70. try
  71. {
  72. da.Fill(ds, "ds");
  73. cmd.Parameters.Clear();
  74. }
  75. catch (System.Data.SqlClient.SqlException ex)
  76. {
  77. throw new Exception(ex.Message);
  78. }
  79. return ds;
  80. }
  81. }
  82. }
  83. /// <summary>
  84. /// 执行SQL语句,返回影响的记录数
  85. /// </summary>
  86. /// <param name="SQLString">SQL语句</param>
  87. /// <returns>影响的记录数</returns>
  88. public static int ExecuteSQL(string SQLString, List<SqlParameter> cmdParms, string connectionString)
  89. {
  90. using (SqlConnection connection = new SqlConnection(connectionString))
  91. {
  92. using (SqlCommand cmd = new SqlCommand())
  93. {
  94. try
  95. {
  96. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  97. int rows = cmd.ExecuteNonQuery();
  98. cmd.Parameters.Clear();
  99. return rows;
  100. }
  101. catch (System.Data.SqlClient.SqlException e)
  102. {
  103. throw e;
  104. }
  105. }
  106. }
  107. }
  108. private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, List<SqlParameter> cmdParms)
  109. {
  110. if (conn.State != ConnectionState.Open)
  111. conn.Open();
  112. cmd.Connection = conn;
  113. cmd.CommandText = cmdText;
  114. if (trans != null)
  115. cmd.Transaction = trans;
  116. cmd.CommandType = CommandType.Text;//cmdType;
  117. if (cmdParms != null)
  118. {
  119. foreach (SqlParameter parameter in cmdParms)
  120. {
  121. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
  122. (parameter.Value == null))
  123. {
  124. parameter.Value = DBNull.Value;
  125. }
  126. cmd.Parameters.Add(parameter);
  127. }
  128. }
  129. }
  130. /// <summary>
  131. /// 创建SQL连接属性
  132. /// </summary>
  133. public static SqlConnection Connection
  134. {
  135. get
  136. {
  137. //DBInitWork();
  138. try
  139. {
  140. if (connection == null)//如果没有创建连接,则先创建
  141. {
  142. //从配置文件中获取SQL连接字段
  143. //string connStr = ConfigurationManager.ConnectionStrings["ConnetcionNmae"].ToString();
  144. connection = new SqlConnection(connString);//创建连接
  145. connection.Open();//打开连接
  146. }
  147. else if (connection.State == ConnectionState.Broken)//如果连接中断,则重现打开
  148. {
  149. connection.Close();
  150. connection.Open();
  151. }
  152. else if (connection.State == ConnectionState.Closed)//如果关闭,则打开
  153. {
  154. connection.Open();
  155. }
  156. return connection;
  157. }
  158. catch (Exception ex)
  159. {
  160. if (connection != null)
  161. {
  162. connection.Close();
  163. connection.Dispose();
  164. }
  165. logNet.WriteError(ex.Message.ToString());
  166. return null;
  167. }
  168. }
  169. }
  170. /// <summary>
  171. /// 重置连接
  172. /// </summary>
  173. public static void ResetConnection()
  174. {
  175. if (connection != null)
  176. {
  177. connection.Close();
  178. connection.Dispose();
  179. connection = null;
  180. }
  181. }
  182. /// <summary>
  183. /// 获取数据集
  184. /// </summary>
  185. /// <param name="str">执行字符串</param>
  186. /// <returns></returns>
  187. public static DataSet GetDataSet(string str)
  188. {
  189. lock (sqlLock)
  190. {
  191. try
  192. {
  193. SqlDataAdapter sda = new SqlDataAdapter(str, Connection);
  194. DataSet ds = new DataSet();
  195. sda.Fill(ds);
  196. return ds;
  197. }
  198. catch (Exception ex)
  199. {
  200. ResetConnection();
  201. logNet.WriteError(ex.Message.ToString());
  202. return null;
  203. }
  204. }
  205. }
  206. /// <summary>
  207. /// 获取表格
  208. /// </summary>
  209. /// <param name="str">执行字符串</param>
  210. /// <returns></returns>
  211. public static DataTable GetDataTable(string str)
  212. {
  213. return GetDataSet(str).Tables[0] ?? null;
  214. }
  215. /// <summary>
  216. /// 执行SQL语句
  217. /// </summary>
  218. /// <param name="str"></param>
  219. public static string ExecuteNonQuery(string str)
  220. {
  221. string ret = string.Empty;
  222. try
  223. {
  224. SqlCommand cmd = new SqlCommand();
  225. cmd.Connection = Connection;
  226. cmd.CommandType = CommandType.Text;
  227. cmd.CommandText = str;
  228. cmd.ExecuteNonQuery();
  229. ret = "成功";
  230. }
  231. catch (Exception ex)
  232. {
  233. ret = ex.Message.ToString();
  234. logNet.WriteError(ex.Message.ToString());
  235. }
  236. return ret;
  237. }
  238. /////////////////////////////////////////////////////////////////////////
  239. ///创建数据库和表
  240. /////////////////////////////////////////////////////////////////////////
  241. /// <summary>
  242. /// 判断数据库是否存在
  243. /// </summary>
  244. /// <param name="db">数据库名称</param>
  245. /// <returns></returns>
  246. public static bool IsDBExist(string db)
  247. {
  248. string createDbStr = " select * from master.dbo.sysdatabases where name " + "= '" + db + "'";
  249. DataTable dt = GetDataTable(createDbStr);
  250. if (dt?.Rows.Count > 0)
  251. {
  252. return true;
  253. }
  254. return false;
  255. }
  256. /// <summary>
  257. /// 判断数据库中指定表格是否存在
  258. /// </summary>
  259. /// <param name="db"></param>
  260. /// <param name="tb"></param>
  261. /// <returns></returns>
  262. public static bool IsTableExist(string db, string tb)
  263. {
  264. string createTbStr = "USE " + db + " select 1 from sysobjects where id =object_id('" + tb + "') and type = 'U'";
  265. DataTable dt = GetDataTable(createTbStr);
  266. if (dt?.Rows.Count > 0)
  267. {
  268. return true;
  269. }
  270. return false;
  271. }
  272. /// <summary>
  273. /// 判断数据库中指定表格是否存在
  274. /// </summary>
  275. /// <param name="db"></param>
  276. /// <param name="tb"></param>
  277. /// <returns></returns>
  278. public static bool IsTableExist(string db, string tb, string connString)
  279. {
  280. string createTbStr = "USE " + db + " select 1 from sysobjects where id =object_id('" + tb + "') and type = 'U'";
  281. DataSet ds = Query(createTbStr, null, connString);
  282. if (ds?.Tables["ds"]?.Rows.Count > 0)
  283. {
  284. return true;
  285. }
  286. return false;
  287. }
  288. /// <summary>
  289. /// 创建数据库表
  290. /// </summary>
  291. /// <param name="db">数据库名</param>
  292. /// <param name="tb">表名</param>
  293. public static void CreateDataTable(string db, string tb, string content)
  294. {
  295. if (IsDBExist(db) == false)
  296. {
  297. throw new Exception("数据库不存在!");
  298. }
  299. if (IsTableExist(db, tb))
  300. {
  301. throw new Exception("数据库表已经存在!");
  302. }
  303. else
  304. {
  305. string createTableStr = "USE " + db + " Create table " + tb + "(" + content + ")";
  306. ExecuteNonQuery(createTableStr);
  307. }
  308. }
  309. public static void CreateDataBase(string dbDir, string subDir, string dataBaseName)
  310. {
  311. string fileMDF = dbDir + subDir + @"\" + dataBaseName + @".mdf";
  312. string fileLDF = dbDir + subDir + @"\" + dataBaseName + @".ldf";
  313. if ((!File.Exists(fileMDF)) && (!File.Exists(fileLDF)))
  314. {
  315. SqlConnection myConn = new SqlConnection("Server=" + GlobalContext.Server
  316. + ";Integrated security=SSPI;database=master");
  317. String strSQL;
  318. strSQL = @"CREATE DATABASE " + dataBaseName +
  319. " ON PRIMARY " +
  320. "(NAME = " + dataBaseName + "_Data, " +
  321. "FILENAME = '" + fileMDF + "', " +
  322. "SIZE = 64MB, " +
  323. "MAXSIZE = UNLIMITED," +
  324. "FILEGROWTH = 64MB)" +
  325. "LOG ON (NAME = " + dataBaseName + "_Log, " +
  326. "FILENAME = '" + fileLDF + "', " +
  327. "SIZE = 64MB, " +
  328. "MAXSIZE = UNLIMITED, " +
  329. "FILEGROWTH = 64MB)";
  330. SqlCommand myCommand = new SqlCommand(strSQL, myConn);
  331. try
  332. {
  333. myConn.Open();
  334. myCommand.ExecuteNonQuery();
  335. logNet.WriteInfo("DataBase is Created Successfully");
  336. //创建StationIn表
  337. string content = @"[GUID] [nvarchar](36) NOT NULL,
  338. [Workorder_code] [nvarchar](50) NOT NULL,
  339. [Mtltmrk] [nvarchar](50) NOT NULL,
  340. [Sn] [nvarchar](64) NOT NULL,
  341. [StationIn_body] [nvarchar](MAX) NOT NULL,
  342. [Parameter_values] [nvarchar](MAX) NULL,
  343. [Write_user] [nvarchar](20) NOT NULL,
  344. [Test_time] [varchar](23) NOT NULL,
  345. [Upload] [nvarchar](10) NOT NULL";
  346. CreateDataTable(dataBaseName, "StationIn", content);
  347. //创建ProcessData表
  348. content = @"[ID] [nvarchar](50) NOT NULL,
  349. [Equipment_code] [nvarchar](50) NOT NULL,
  350. [Workorder_code] [nvarchar](50) NOT NULL,
  351. [Batch_number] [nvarchar](32) NULL,
  352. [Sn] [nvarchar](64) NULL,
  353. [Testitem] [varchar](50) NULL,
  354. [Parameter_values] [nvarchar](MAX) NOT NULL,
  355. [Write_user] [nvarchar](20) NOT NULL,
  356. [Test_time] [varchar](23) NOT NULL,
  357. [Upload] [nvarchar](10) NOT NULL";
  358. CreateDataTable(dataBaseName, "ProcessData", content);
  359. //创建OneCheckData表
  360. content = @" [ID] [nvarchar](50) NOT NULL,
  361. [Line_code] [nvarchar](50) NOT NULL,
  362. [Line_name] [nvarchar](50) NOT NULL,
  363. [Equipment_code] [nvarchar](50) NOT NULL,
  364. [Equipment_name] [nvarchar](50) NOT NULL,
  365. [Workorder_code] [nvarchar](50) NOT NULL,
  366. [Procedure_code] [nvarchar](32) NOT NULL,
  367. [Procedure_name] [nvarchar](32) NOT NULL,
  368. [Oneckeck_values] [nvarchar](MAX) NOT NULL,
  369. [Onecheck_empcode] [nvarchar](32) NULL,
  370. [Onecheck_empname] [nvarchar](32) NULL,
  371. [Onecheck_time] [varchar](20) NOT NULL,
  372. [Upload] [nvarchar](10) NOT NULL";
  373. CreateDataTable(dataBaseName, "OneCheckData", content);
  374. //创建WorkingData表-单机
  375. content = @"
  376. [Date] [nvarchar](10) NOT NULL,
  377. [Equipment_code] [nvarchar](32) NOT NULL,
  378. [BootTime] [varchar](20) NOT NULL,
  379. [Bootmoment] [nvarchar](20) NOT NULL,
  380. [RunTime] [varchar](20) NOT NULL,
  381. [WoringTime] [varchar](20) NOT NULL,
  382. [RepairTime] [varchar](20) NOT NULL,
  383. [StopTime] [varchar](20) NOT NULL,
  384. [WoringNum] [nvarchar](20) NOT NULL,
  385. [NeedTime] [varchar](20) NOT NULL,
  386. [PlanStopMoment] [nvarchar](20) NOT NULL,
  387. [Equipment_status] [nvarchar](20) NOT NULL,
  388. [WorkingQty] [nchvarcharar](20) NOT NULL,
  389. [QualifiedQty] [nvarchar](20) NOT NULL,
  390. [TotalQty] [nvarchar](20) NOT NULL,
  391. [NGset] [nvarchar](20) NOT NULL,
  392. [QualifiedRateSet] [nvarchar](20) NOT NULL,
  393. [RhySet] [nvarchar](20) NOT NULL,
  394. [Update_time] [varchar](20) NOT NULL";
  395. CreateDataTable(dataBaseName, "WorkingData", content);
  396. //创建LineWorkingData表-整线
  397. content = @" [GUID] [nvarchar](36) NOT NULL,
  398. [LineName] [nvarchar](36) NOT NULL,
  399. [BootTimeLong] [float] NULL,
  400. [NormalTimeLong] [float] NULL,
  401. [StandbyTimeLong] [float] NULL,
  402. [FaultTimeLong] [float] NULL,
  403. [MaterialShortageTimeLong] [float] NULL,
  404. [MaintenanceTimeLong] [float] NULL,
  405. [FaultNumber] [int] NULL,
  406. [OutputNumber] [int] NULL,
  407. [QualifiedNumber] [int] NULL,
  408. [QualifiedRate] [float] NULL,
  409. [DesignRhythm] [float] NULL,
  410. [RealityRhythm] [float] NULL,
  411. [CreateTime] [datetime] NULL";
  412. CreateDataTable(dataBaseName, "LineWorkingData", content);
  413. //创建AlarmData表
  414. content = @" [GUID] [nvarchar](36) NOT NULL,
  415. [LineName] [nvarchar](36) NOT NULL,
  416. [AlarmType] [nvarchar](36) NOT NULL,
  417. [AlarmDesc] [nvarchar](64) NOT NULL,
  418. [StartTime] [datetime] NOT NULL,
  419. [EndTime] [datetime] NULL,
  420. [PersistTime] [int] NULL";
  421. CreateDataTable(dataBaseName, "AlarmData", content);
  422. }
  423. catch (System.Exception ex)
  424. {
  425. logNet.WriteError(ex.Message.ToString());
  426. }
  427. finally
  428. {
  429. if (myConn.State == ConnectionState.Open)
  430. {
  431. myConn.Close();
  432. }
  433. }
  434. }
  435. }
  436. #region
  437. /// <summary>
  438. /// 检验并创建工单信息表
  439. /// </summary>
  440. public static void CreateDataBase_DBMain()
  441. {
  442. try
  443. {
  444. // 数据库链接
  445. string connString =
  446. "server=" + GlobalContext.Server +
  447. ";database=DBMain" +
  448. ";uid=" + GlobalContext.User +
  449. ";pwd=" + GlobalContext.PassWord;
  450. // 创建OrderTable表
  451. if (!IsTableExist("DBMain", "OrderTable", connString))
  452. {
  453. string content =
  454. @"
  455. CREATE TABLE [dbo].[OrderTable](
  456. [WorkOrderNum] [nvarchar](150) NOT NULL,
  457. [WorkOrderStatus] [nvarchar](32) NOT NULL,
  458. [BatchNumber] [nvarchar](36) NULL,
  459. [ProductMtltmrk] [nvarchar](32) NULL,
  460. [ProductNo] [nvarchar](32) NULL,
  461. [ProductName] [nvarchar](32) NULL,
  462. [SupplierCode] [nvarchar](32) NULL,
  463. [PlannedQuantity] [nvarchar](32) NULL,
  464. [CompletedQuantity] [int] NULL,
  465. [Plnsign] [nvarchar](32) NULL,
  466. [Soreqdat] [nvarchar](32) NULL,
  467. [Process] [nvarchar](32) NULL,
  468. [CreatedTime] [datetime] NOT NULL,
  469. CONSTRAINT [PK__OrderTab__33E32040C02E055A] PRIMARY KEY CLUSTERED
  470. (
  471. [WorkOrderNum] ASC
  472. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  473. ) ON [PRIMARY]
  474. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'车间订单号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'OrderTable', @level2type=N'COLUMN',@level2name=N'WorkOrderNum'
  475. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'订单状态' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'OrderTable', @level2type=N'COLUMN',@level2name=N'WorkOrderStatus'
  476. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'批次号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'OrderTable', @level2type=N'COLUMN',@level2name=N'BatchNumber'
  477. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'产品型号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'OrderTable', @level2type=N'COLUMN',@level2name=N'ProductMtltmrk'
  478. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'产品代号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'OrderTable', @level2type=N'COLUMN',@level2name=N'ProductNo'
  479. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'产品名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'OrderTable', @level2type=N'COLUMN',@level2name=N'ProductName'
  480. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'供应商代码' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'OrderTable', @level2type=N'COLUMN',@level2name=N'SupplierCode'
  481. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'计划数量' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'OrderTable', @level2type=N'COLUMN',@level2name=N'PlannedQuantity'
  482. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'已完成数量' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'OrderTable', @level2type=N'COLUMN',@level2name=N'CompletedQuantity'
  483. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'计划标记' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'OrderTable', @level2type=N'COLUMN',@level2name=N'Plnsign'
  484. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'需求日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'OrderTable', @level2type=N'COLUMN',@level2name=N'Soreqdat'
  485. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'所属流程' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'OrderTable', @level2type=N'COLUMN',@level2name=N'Process'
  486. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'订单创建时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'OrderTable', @level2type=N'COLUMN',@level2name=N'CreatedTime'
  487. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'订单信息表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'OrderTable'";
  488. ExecuteSQL(content, null, connString);
  489. }
  490. }
  491. catch (System.Exception ex)
  492. {
  493. logNet.WriteError(ex.Message.ToString());
  494. }
  495. }
  496. #endregion
  497. #region 进出站相关数据记录
  498. //连接本地数据库
  499. public static SqlSugarClient db = new SqlSugarClient(new ConnectionConfig
  500. {
  501. ConnectionString = connString, // 连接到 SqlServer(不指定数据库)
  502. DbType = SqlSugar.DbType.SqlServer, // 数据库类型:SqlServer
  503. IsAutoCloseConnection = true, // 自动关闭连接
  504. InitKeyType = InitKeyType.Attribute // 使用实体类属性来初始化表结构
  505. });
  506. //连网数据库
  507. public static SqlSugarClient dbmain = new SqlSugarClient(new ConnectionConfig
  508. {
  509. ConnectionString = "server=" + GlobalContext.Server +
  510. ";database=DBMain" +
  511. ";uid=" + GlobalContext.User +
  512. ";pwd=" + GlobalContext.PassWord, // 连接到 SqlServer(不指定数据库)
  513. DbType = SqlSugar.DbType.SqlServer, // 数据库类型:SqlServer
  514. IsAutoCloseConnection = true, // 自动关闭连接
  515. InitKeyType = InitKeyType.Attribute // 使用实体类属性来初始化表结构
  516. });
  517. // 判断表格是否存在
  518. public static bool CheckTableExists(SqlSugarClient db, string tableName)
  519. {
  520. //判断表是否存在
  521. var result = db.Ado.SqlQuery<int>($@"
  522. SELECT COUNT(*)
  523. FROM INFORMATION_SCHEMA.TABLES
  524. WHERE TABLE_NAME = @tableName", new { tableName }).FirstOrDefault() > 0;
  525. return result;
  526. }
  527. //创建 载具绑定物料码表、物料码绑定部件码表、PLC返回MES数据记录表
  528. public static void CreateDataBase()
  529. {
  530. try
  531. {
  532. // 3. 判断并创建表格
  533. if (!CheckTableExists(dbmain, "carrierbind"))
  534. {
  535. CreateTables<CarrierBind>(dbmain);
  536. }
  537. if (!CheckTableExists(db, "productbind"))
  538. {
  539. CreateTables<ProductBind>(db);
  540. }
  541. if (!CheckTableExists(db, "testdata"))
  542. {
  543. CreateTables<TestData>(db);
  544. }
  545. logNet.WriteInfo("表格已创建或已存在。");
  546. }
  547. catch (Exception ex)
  548. {
  549. logNet.WriteError("表格创建失败,错误原因:" + ex.Message);
  550. MessageBox.Show("表格创建失败,错误码:" + ex.Message);
  551. }
  552. }
  553. public static void CreateTables<T>(SqlSugarClient db) where T : class, new()
  554. {
  555. db.CodeFirst.InitTables<T>(); // 根据传入的实体类类型来创建表格
  556. logNet.WriteInfo($"表格 {typeof(T).Name} 已创建。");
  557. }
  558. //获取载具绑定的产品码
  559. public static string GetProductBarcodeByCarrierCode(string CarrierCode)
  560. {
  561. string ProductBarcode = db.Queryable<CarrierBind>()
  562. .Where(x => x.CarrierCode == CarrierCode)
  563. .OrderByDescending(x => x.ID)
  564. .Select(x => x.ProductBarcode)
  565. .First();
  566. return ProductBarcode;
  567. }
  568. //载具码和产品码绑定关系
  569. public static ResponseMessage InsertCarrierBind(string carrierCode, string productBarcode, string stationId)
  570. {
  571. #region 新建CarrierBind实体,并将数据插入carrierBind表格
  572. // 创建 CarrierBind 实体,并通过传入的参数设置字段值
  573. var CarrierBind_sumRecord = new CarrierBind
  574. {
  575. CarrierCode = carrierCode,
  576. ProductBarcode = productBarcode
  577. };
  578. // 检查记录是否已经存在
  579. var CarrierBind_exists = db.Queryable<CarrierBind>().Where(x => x.CarrierCode == carrierCode);
  580. try
  581. {
  582. if (CarrierBind_exists != null)
  583. {
  584. db.Deleteable<CarrierBind>().Where(x => x.CarrierCode == carrierCode).ExecuteCommand();
  585. logNet.WriteInfo($"载具码与产品码已存在绑定关系,先解绑。");
  586. }
  587. // 插入数据
  588. db.Insertable(CarrierBind_sumRecord).ExecuteCommand();
  589. logNet.WriteInfo($"载具码与产品码绑定成功。");
  590. return new ResponseMessage { result = true, text = "载具码与产品码绑定成功" };
  591. }
  592. catch (Exception ex)
  593. {
  594. logNet.WriteError($"载具码与产品码绑定失败,错误" + ex.Message);
  595. return new ResponseMessage { result = false, text = "载具码与产品码绑定失败,错误" + ex.Message };
  596. }
  597. #endregion
  598. }
  599. public static ResponseMessage InsertOp10Data( string carrierCode, string productBarcode, int bindOrder,
  600. int throwingAmount, float cleaningPressure, float cleaningSpeed,
  601. float airKnifeHeight, float cleaningTime, int cleaningCount,int remainCount)
  602. {
  603. // 检查记录是否已经存在
  604. bool OP10_exists = db.Queryable<CarrierBind>().Any(x => x.CarrierCode == carrierCode &&
  605. x.ProductBarcode == productBarcode);
  606. if (OP10_exists)
  607. {
  608. var maxBindOrder = db.Queryable<TestData>()
  609. .Where(x => x.CarrierCode == carrierCode &&
  610. x.ProductBarcode == productBarcode)
  611. .Max(x => x.BindOrder); ;
  612. bindOrder = maxBindOrder + 1;
  613. }
  614. #region 将OP10数据插入testdata表格
  615. // 创建 Op10 实体,并通过传入的参数设置字段值
  616. var op10 = new TestData
  617. {
  618. CarrierCode = carrierCode, // 载具码
  619. ProductBarcode = productBarcode, // 产品码
  620. BindOrder = bindOrder, // 绑定顺序
  621. OP10_ThrowingAmount = throwingAmount, // 抛料数量
  622. OP10_CleaningPressure = cleaningPressure, // 清洗气压
  623. OP10_CleaningSpeed = cleaningSpeed, // 清洗速度
  624. OP10_AirKnifeHeight = airKnifeHeight, // 风刀高度
  625. OP10_CleaningTime = cleaningTime, // 清洗时间
  626. OP10_CleaningCount = cleaningCount, // 清洗次数
  627. OP10_RemainCount = cleaningCount // 清洗次数
  628. };
  629. try
  630. {
  631. db.Insertable(op10).ExecuteCommand();
  632. logNet.WriteError("OP10记录插入成功!");
  633. return new ResponseMessage { result = true, text = "OP10记录插入成功"};
  634. }
  635. catch (Exception ex)
  636. {
  637. logNet.WriteError("OP10记录插入出错!错误码:" + ex.Message);
  638. return new ResponseMessage { result = false, text = "OP10记录插入出错!错误码:" + ex.Message };
  639. }
  640. #endregion
  641. }
  642. // op20绑定部件码
  643. public static ResponseMessage InsertOp20Product(string carrierCode, string productBarcode, string topCover_Barcode)
  644. {
  645. int bindOrder = 1;
  646. // 检查记录是否已经存在
  647. bool Product_exists = db.Queryable<ProductBind>().Any(x => x.CarrierCode == carrierCode &&
  648. x.ProductBarcode == productBarcode);
  649. if (Product_exists)
  650. {
  651. var maxBindOrder = db.Queryable<ProductBind>()
  652. .Where(x => x.CarrierCode == carrierCode &&
  653. x.ProductBarcode == productBarcode)
  654. .Max(x => x.BindOrder); ;
  655. bindOrder = maxBindOrder + 1;
  656. }
  657. #region 新建ProductBind实体,并将数据插入productBind表格
  658. // 创建 ProductBind 实体,并通过传入的参数设置字段值
  659. var ProductBind_sumRecord = new ProductBind
  660. {
  661. CarrierCode = carrierCode,//载具码
  662. ProductBarcode = productBarcode, // 产品条码
  663. BindOrder = bindOrder, // 绑定顺序
  664. TopCover_Barcode=topCover_Barcode, //部件码
  665. };
  666. // 插入数据
  667. try
  668. {
  669. db.Insertable(ProductBind_sumRecord).ExecuteCommand();
  670. return new ResponseMessage { result = true, text = "OP20-产品码绑定部件码成功!" };
  671. }
  672. catch (Exception ex)
  673. {
  674. logNet.WriteError("OP20-产品码绑定部件码出错!错误码:" + ex.Message);
  675. return new ResponseMessage { result = false, text = "OP20-产品码绑定部件码出错!错误码:" + ex.Message };
  676. }
  677. #endregion
  678. }
  679. // op20向testdata表格插入数据
  680. public static ResponseMessage InsertOp20Data(string carrierCode, string productBarcode, int throwCount, int remainCount)
  681. {
  682. ////// 检查上一次插入的记录是否存在
  683. ////var lastRecord = db.Queryable<TestData>()
  684. //// .Where(x => x.CarrierCode== carrierCode && x.ProductBarcode == productBarcode &&
  685. //// (x.OP10_ThrowingAmount != 0 ||
  686. //// x.OP10_CleaningPressure != 0.0f ||
  687. //// x.OP10_CleaningSpeed != 0.0f ||
  688. //// x.OP10_AirKnifeHeight != 0.0f ||
  689. //// x.OP10_CleaningTime != 0.0f ||
  690. //// x.OP10_CleaningCount != 0 ||
  691. //// x.OP10_RemainCount != 0)) // 看上一次有无记录数据
  692. //// .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  693. //// .Take(1) // 只取一条记录
  694. //// .First(); // 获取第一条记录,若没有则返回null
  695. ////if (lastRecord == null)
  696. ////{
  697. //// logNet.WriteError("OP20错误:OP10未插入数据!");
  698. ////}
  699. var lastRecord = db.Queryable<TestData>()
  700. .Where(x => x.CarrierCode == carrierCode && x.ProductBarcode == productBarcode )
  701. .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  702. .Take(1) // 只取一条记录
  703. .First(); // 获取第一条记录,若没有则返回null
  704. if (lastRecord == null)
  705. {
  706. logNet.WriteError("OP20记录插入出错:MES主数据未成功创建,无法插入OP20数据!");
  707. return new ResponseMessage { result = false, text = "OP20错误:MES主数据未成功创建,无法插入OP20数据!" };
  708. }
  709. if (lastRecord.OP20_ThrowCount != 0 || lastRecord.OP20_RemainCount != 0)
  710. {
  711. logNet.WriteError("OP20记录插入出错:即将插入的行数据已存在,插入失败!");
  712. return new ResponseMessage { result = false, text = "OP20记录插入出错:即将插入的行数据已存在,插入失败!" };
  713. }
  714. lastRecord.OP20_ThrowCount = throwCount;
  715. lastRecord.OP20_RemainCount = remainCount;
  716. try
  717. {
  718. db.Updateable(lastRecord)
  719. .UpdateColumns(x => new { x.OP20_ThrowCount, x.OP20_RemainCount })
  720. .ExecuteCommand();
  721. logNet.WriteError("OP20记录插入成功!");
  722. return new ResponseMessage { result = false, text = "OP20记录插入成功!" };
  723. }
  724. catch (Exception ex)
  725. {
  726. logNet.WriteError("OP20记录插入出错!错误码:" + ex.Message);
  727. return new ResponseMessage { result = false, text = "OP20记录插入出错!错误码:" + ex.Message };
  728. }
  729. }
  730. // op301向testdata表格插入数据
  731. public static ResponseMessage InsertOp301Data(string carrierCode, string productBarcode, float gluingSpeed, float pressureAB, float pressureDifferenceAB,
  732. float productHeightInfo, float periodicWeightData, float remainingGlueAmount)
  733. {
  734. ////// 检查上一次插入的记录是否存在
  735. ////var lastRecord = db.Queryable<TestData>()
  736. //// .Where(x => x.CarrierCode == carrierCode && x.ProductBarcode == productBarcode &&
  737. //// (x.OP20_ThrowCount != 0 || x.OP20_RemainCount != 0)) // 只查找有效插入的数据
  738. //// .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  739. //// .Take(1) // 只取一条记录
  740. //// .First(); // 获取第一条记录,若没有则返回null
  741. ////if (lastRecord == null)
  742. ////{
  743. //// logNet.WriteError("OP301错误:OP20插入的记录存在值为空!");
  744. //// return new ResponseMessage { result = false, text = "OP301错误:OP20插入的记录存在值为空!" };
  745. ////}
  746. var lastRecord = db.Queryable<TestData>()
  747. .Where(x => x.CarrierCode == carrierCode && x.ProductBarcode == productBarcode)
  748. .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  749. .Take(1) // 只取一条记录
  750. .First(); // 获取第一条记录,若没有则返回null
  751. if (lastRecord == null)
  752. {
  753. logNet.WriteError("OP301错误:MES主数据未成功创建,无法插入OP301数据!");
  754. return new ResponseMessage { result = false, text = "OP301错误:MES主数据未成功创建,无法插入OP20数据!" };
  755. }
  756. if (lastRecord.OP301_GluingSpeed != 0.0f || lastRecord.OP301_PressureAB != 0.0f ||
  757. lastRecord.OP301_PressureDifferenceAB != 0.0f || lastRecord.OP301_ProductHeightInfo != 0.0f ||
  758. lastRecord.OP301_PeriodicWeightData != 0.0f || lastRecord.OP301_RemainingGlueAmount != 0.0f)
  759. {
  760. logNet.WriteError("OP301记录插入出错:即将插入的行数据已存在,插入失败!");
  761. return new ResponseMessage { result = false, text = "OP301记录插入出错:即将插入的行数据已存在,插入失败!" };
  762. }
  763. lastRecord.OP301_GluingSpeed = gluingSpeed; // 供胶速度
  764. lastRecord.OP301_PressureAB = pressureAB; // AB管气压
  765. lastRecord.OP301_PressureDifferenceAB = pressureDifferenceAB; // AB管气压差
  766. lastRecord.OP301_ProductHeightInfo = productHeightInfo; // 产品测高信息
  767. lastRecord.OP301_PeriodicWeightData = periodicWeightData; // 定期称重数据
  768. lastRecord.OP301_RemainingGlueAmount = remainingGlueAmount; // 剩余胶量
  769. try
  770. {
  771. db.Updateable(lastRecord)
  772. .UpdateColumns(x => new {
  773. x.OP301_GluingSpeed,
  774. x.OP301_PressureAB,
  775. x.OP301_PressureDifferenceAB,
  776. x.OP301_ProductHeightInfo,
  777. x.OP301_PeriodicWeightData,
  778. x.OP301_RemainingGlueAmount
  779. }).ExecuteCommand();
  780. logNet.WriteError("OP301记录插入成功!");
  781. return new ResponseMessage { result = true, text = "OP301记录插入成功"};
  782. }
  783. catch (Exception ex)
  784. {
  785. logNet.WriteError("OP301记录插入出错!错误码:" + ex.Message);
  786. return new ResponseMessage { result = false, text = "OP301记录插入出错!错误码:" + ex.Message };
  787. }
  788. }
  789. // op302向testdata表格插入数据
  790. public static ResponseMessage InsertOp302Data(string carrierCode, string productBarcode, float gluingSpeed, float pressureAB, float pressureDifferenceAB,
  791. float productHeightInfo, float periodicWeightData, float remainingGlueAmount)
  792. {
  793. ////// 检查上一次插入的记录是否存在
  794. ////var lastRecord = db.Queryable<TestData>()
  795. //// .Where(x => x.OP301_GluingSpeed != 0.0f && x.OP301_PressureA != 0.0f && x.OP301_PressureB != 0.0f &&
  796. //// x.OP301_PressureDifferenceAB != 0.0f && x.OP301_ProductHeightInfo != 0.0f &&
  797. //// x.OP301_PeriodicWeightData != 0.0f && x.OP301_RemainingGlueAmount != 0.0f) // 只查找有效插入的数据
  798. //// .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  799. //// .Take(1) // 只取一条记录
  800. //// .First(); // 获取第一条记录,若没有则返回null
  801. ////if (lastRecord == null)
  802. ////{
  803. //// logNet.WriteError("OP302错误:OP301插入的记录存在值为空!");
  804. //// return new ResponseMessage { result = false, text = "OP302错误:OP301插入的记录存在值为空!" };
  805. ////}
  806. ///
  807. var lastRecord = db.Queryable<TestData>()
  808. .Where(x => x.CarrierCode == carrierCode && x.ProductBarcode == productBarcode)
  809. .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  810. .Take(1) // 只取一条记录
  811. .First(); // 获取第一条记录,若没有则返回null
  812. if (lastRecord == null)
  813. {
  814. logNet.WriteError("OP302记录插入错误:MES主数据未成功创建,无法插入OP302数据!");
  815. return new ResponseMessage { result = false, text = "OP302记录插入错误:MES主数据未成功创建,无法插入OP20数据!" };
  816. }
  817. if (lastRecord.OP302_GluingSpeed != 0.0f || lastRecord.OP302_PressureAB != 0.0f ||
  818. lastRecord.OP302_PressureDifferenceAB != 0.0f || lastRecord.OP302_ProductHeightInfo != 0.0f ||
  819. lastRecord.OP302_PeriodicWeightData != 0.0f || lastRecord.OP302_RemainingGlueAmount != 0.0f)
  820. {
  821. logNet.WriteError("OP302记录插入出错:即将插入的行数据已存在,插入失败!");
  822. return new ResponseMessage { result = false, text = "OP302记录插入出错:即将插入的行数据已存在,插入失败!" };
  823. }
  824. lastRecord.OP302_GluingSpeed = gluingSpeed; // 供胶速度
  825. lastRecord.OP302_PressureAB = pressureAB; // AB管气压
  826. lastRecord.OP302_PressureDifferenceAB = pressureDifferenceAB; // AB管气压差
  827. lastRecord.OP302_ProductHeightInfo = productHeightInfo; // 产品测高信息
  828. lastRecord.OP302_PeriodicWeightData = periodicWeightData; // 定期称重数据
  829. lastRecord.OP302_RemainingGlueAmount = remainingGlueAmount; // 剩余胶量
  830. try
  831. {
  832. db.Updateable(lastRecord)
  833. .UpdateColumns(x => new {
  834. x.OP302_GluingSpeed,
  835. x.OP302_PressureAB,
  836. x.OP302_PressureDifferenceAB,
  837. x.OP302_ProductHeightInfo,
  838. x.OP302_PeriodicWeightData,
  839. x.OP302_RemainingGlueAmount
  840. }).ExecuteCommand();
  841. logNet.WriteError("OP302记录插入成功!");
  842. return new ResponseMessage { result = true, text = "OP302记录插入成功" };
  843. }
  844. catch (Exception ex)
  845. {
  846. logNet.WriteError("OP302记录插入出错!错误码:" + ex.Message);
  847. return new ResponseMessage { result = false, text = "OP302错误:即将插入的数据存在值不为空,插入失败,请按标准操作!" };
  848. }
  849. }
  850. // op40向testdata表格插入数据
  851. public static ResponseMessage InsertOp40Data(string carrierCode, string productBarcode, float gluePosx, float gluePosy, float glueLineArea,
  852. float glueLineHeight,int result, string inspectionImagePath)
  853. {
  854. //// 检查上一次插入的记录是否存在
  855. //var lastRecord = db.Queryable<TestData>()
  856. // .Where(x => x.OP302_GluingSpeed != 0.0f && x.OP302_PressureAB != 0.0f &&
  857. // x.OP302_PressureDifferenceAB != 0.0f && x.OP302_ProductHeightInfo != 0.0f &&
  858. // x.OP302_PeriodicWeightData != 0.0f && x.OP302_RemainingGlueAmount != 0.0f) // 只查找有效插入的数据
  859. // .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  860. // .Take(1) // 只取一条记录
  861. // .First(); // 获取第一条记录,若没有则返回null
  862. //if (lastRecord == null)
  863. //{
  864. // logNet.WriteError("OP40错误:OP302插入的记录存在值为空!");
  865. // return new ResponseMessage { result = false, text = "OP40错误:OP302插入的记录存在值为空!" };
  866. //}
  867. //if (lastRecord.OP40_GluePosition != "" || lastRecord.OP40_GlueLineArea != 0.0f ||
  868. // lastRecord.OP40_GlueLineHeight != 0.0f || lastRecord.OP40_InspectionImagePath != "")
  869. //{
  870. // logNet.WriteError("OP40错误:即将插入的数据存在值不为空,插入失败,请按标准操作!");
  871. // return new ResponseMessage { result = false, text = "OP40错误:即将插入的数据存在值不为空,插入失败,请按标准操作!" };
  872. //}
  873. var lastRecord = db.Queryable<TestData>()
  874. .Where(x => x.CarrierCode == carrierCode && x.ProductBarcode == productBarcode)
  875. .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  876. .Take(1) // 只取一条记录
  877. .First(); // 获取第一条记录,若没有则返回null
  878. if (lastRecord == null)
  879. {
  880. logNet.WriteError("OP40记录插入错误:MES主数据未成功创建,无法插入OP40数据!");
  881. return new ResponseMessage { result = false, text = "OP40记录插入错误:MES主数据未成功创建,无法插入OP20数据!" };
  882. }
  883. if (lastRecord.OP40_GluePosX != 0.0f || lastRecord.OP40_GluePosY != 0.0f || lastRecord.OP40_GlueLineArea != 0.0f ||
  884. lastRecord.OP40_GlueLineHeight != 0.0f || lastRecord.OP40_Result != 0 || lastRecord.OP40_InspectionImagePath != "")
  885. {
  886. logNet.WriteError("OP40记录插入出错:即将插入的行数据已存在,插入失败!");
  887. return new ResponseMessage { result = false, text = "OP40记录插入出错:即将插入的行数据已存在,插入失败!" };
  888. }
  889. lastRecord.OP40_GluePosX = gluePosx; // 胶线位置X偏差
  890. lastRecord.OP40_GluePosY = gluePosy; // 胶线位置Y偏差
  891. lastRecord.OP40_GlueLineArea = glueLineArea; // 胶线面积
  892. lastRecord.OP40_GlueLineHeight = glueLineHeight; // 胶线高度
  893. lastRecord.OP40_Result = result; // 胶线检测结果
  894. lastRecord.OP40_InspectionImagePath = inspectionImagePath; // 检测图片路径
  895. try
  896. {
  897. db.Updateable(lastRecord)
  898. .UpdateColumns(x => new {
  899. x.OP40_GluePosX,
  900. x.OP40_GluePosY,
  901. x.OP40_GlueLineArea,
  902. x.OP40_GlueLineHeight,
  903. x.OP40_Result,
  904. x.OP40_InspectionImagePath
  905. }).ExecuteCommand();
  906. logNet.WriteError("OP40记录插入成功!");
  907. return new ResponseMessage { result = true, text = "OP40记录插入成功!" };
  908. }
  909. catch (Exception ex)
  910. {
  911. logNet.WriteError("OP40记录插入出错!错误码:" + ex.Message);
  912. return new ResponseMessage { result = true, text = "OP40记录插入出错!错误码:" + ex.Message };
  913. }
  914. }
  915. //OP50 往product塞数据
  916. public static ResponseMessage InsertOp50Product( string carrierCode,string productBarcode, string addPCB_Barcode)
  917. {
  918. #region 往productBind表格中插入addPCB_Barcode数据
  919. // 检查上一次插入的记录是否存在
  920. var productBind_lastRecord = db.Queryable<ProductBind>()
  921. .Where(x => x.CarrierCode == carrierCode && x.ProductBarcode == productBarcode && x.BindOrder != 0)
  922. .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  923. .Take(1) // 只取一条记录
  924. .First(); // 获取第一条记录,若没有则返回null
  925. if (productBind_lastRecord == null)
  926. {
  927. logNet.WriteError("OP50-错误:ProductBind表数据为空!");
  928. return new ResponseMessage { result = false, text = "OP50-错误:ProductBind表数据为空!" };
  929. }
  930. if (productBind_lastRecord.AddPCB_Barcode != "")
  931. {
  932. logNet.WriteError("OP50-错误:即将插入ProductBind的数据存在值不为空,插入失败,请按标准操作!");
  933. return new ResponseMessage { result = false, text = "OP50-错误:即将插入ProductBind的数据存在值不为空,插入失败,请按标准操作!" };
  934. }
  935. productBind_lastRecord.AddPCB_Barcode = addPCB_Barcode;
  936. try
  937. {
  938. db.Updateable(productBind_lastRecord)
  939. .UpdateColumns(x => new {
  940. x.AddPCB_Barcode
  941. }).ExecuteCommand();
  942. logNet.WriteError("OP50部件码绑定产品码成功!");
  943. return new ResponseMessage { result = false, text = "OP50部件码绑定产品码成功!" };
  944. }
  945. catch (Exception ex)
  946. {
  947. logNet.WriteError("OP50部件码绑定产品码失败!错误码:" + ex.Message);
  948. return new ResponseMessage { result = false, text = "OP50部件码绑定产品码失败!错误码:" + ex.Message };
  949. }
  950. #endregion
  951. }
  952. // op50向testdata表格插入数据
  953. public static ResponseMessage InsertOp50Data(string carrierCode,string productBarcode,int assemblyStatus,
  954. int addBoardStatus, float addBoardPressure,int remainCount, string reinspectionImagePath)
  955. {
  956. // 检查上一次插入的记录是否存在
  957. //var lastRecord = db.Queryable<TestData>()
  958. // .Where(x => x.CarrierCode == CarrierCode && x.ProductBarcode == ProductBarcode && x.OP40_GluePosition != "" && x.OP40_GlueLineArea != 0.0f &&
  959. // x.OP40_GlueLineHeight != 0.0f && x.OP40_InspectionImagePath != "") // 只查找有效插入的数据
  960. // .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  961. // .Take(1) // 只取一条记录
  962. // .First(); // 获取第一条记录,若没有则返回null
  963. //if (lastRecord == null)
  964. //{
  965. // logNet.WriteError("OP50错误:OP40插入的记录存在值为空!");
  966. // return new ResponseMessage { result = false, text = "OP50错误:OP40插入的记录存在值为空!!" };
  967. var lastRecord = db.Queryable<TestData>()
  968. .Where(x => x.CarrierCode == carrierCode && x.ProductBarcode == productBarcode)
  969. .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  970. .Take(1) // 只取一条记录
  971. .First(); // 获取第一条记录,若没有则返回null
  972. if (lastRecord == null)
  973. {
  974. logNet.WriteError("OP50记录插入错误:MES主数据未成功创建,无法插入OP40数据!");
  975. return new ResponseMessage { result = false, text = "OP50记录插入错误:MES主数据未成功创建,无法插入OP20数据!" };
  976. }
  977. if ( lastRecord.OP50_AssemblyStatus != 2 || lastRecord.OP50_ReinspectionImagePath != "" ||
  978. lastRecord.OP50_AddBoardStatus != 2 || lastRecord.OP50_AddBoardPressure != 0.0f)
  979. {
  980. logNet.WriteError("OP50错误:即将插入的数据存在值不为空,插入失败,请按标准操作!");
  981. return new ResponseMessage { result = false, text = "OP50错误:即将插入的数据存在值不为空,插入失败,请按标准操作!" };
  982. }
  983. lastRecord.OP50_AssemblyStatus = assemblyStatus; // 组装是否到位
  984. lastRecord.OP50_AddBoardStatus = addBoardStatus; // ADD板有无
  985. lastRecord.OP50_AddBoardPressure = addBoardPressure; // ADD板压合压力
  986. lastRecord.OP50_RemainCount = remainCount; // ADD板余料数
  987. lastRecord.OP50_ReinspectionImagePath = reinspectionImagePath; // ADD板余料数
  988. try
  989. {
  990. db.Updateable(lastRecord)
  991. .UpdateColumns(x => new {
  992. x.OP50_AssemblyStatus,
  993. x.OP50_AddBoardStatus,
  994. x.OP50_AddBoardPressure,
  995. x.OP50_RemainCount,
  996. x.OP50_ReinspectionImagePath
  997. }).ExecuteCommand();
  998. logNet.WriteError("OP50记录插入成功!");
  999. return new ResponseMessage { result = true, text = "OP50记录插入成功!" };
  1000. }
  1001. catch (Exception ex)
  1002. {
  1003. logNet.WriteError("OP50记录插入出错!错误码:" + ex.Message);
  1004. return new ResponseMessage { result = false, text = "OP50记录插入出错!错误码:" + ex.Message };
  1005. }
  1006. }
  1007. // op60向testdata表格插入数据
  1008. public static ResponseMessage InsertOp60Data(string CarrierCode,string ProductBarcode, int assemblyStatus, string reinspectionImagePath,
  1009. int topCoverStatus, float topCoverPressure)
  1010. {
  1011. // 检查上一次插入的记录是否存在
  1012. var lastRecord = db.Queryable<TestData>()
  1013. .Where(x => x.CarrierCode == CarrierCode && x.ProductBarcode == ProductBarcode && x.AddPCB_Barcode != "" && x.OP50_AssemblyStatus != 2 && x.OP50_ReinspectionImagePath != "" &&
  1014. x.OP50_AddBoardStatus != 2 && x.OP50_AddBoardPressure != 0.0f) // 只查找有效插入的数据
  1015. .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  1016. .Take(1) // 只取一条记录
  1017. .First(); // 获取第一条记录,若没有则返回null
  1018. if (lastRecord == null)
  1019. {
  1020. logNet.WriteError("OP60错误:OP50插入的记录存在值为空!");
  1021. return new ResponseMessage { result = false, text = "OP60错误:OP50插入的记录存在值为空!" };
  1022. }
  1023. if (lastRecord.OP60_AssemblyStatus != 2 || lastRecord.OP60_ReinspectionImagePath != "" ||
  1024. lastRecord.OP60_TopCoverStatus != 2 || lastRecord.OP60_TopCoverPressure != 0.0f)
  1025. {
  1026. logNet.WriteError("OP60错误:即将插入的数据存在值不为空,插入失败,请按标准操作!");
  1027. return new ResponseMessage { result = false, text = "OP60错误:即将插入的数据存在值不为空,插入失败,请按标准操作!" };
  1028. }
  1029. lastRecord.OP60_AssemblyStatus = assemblyStatus; // 组装是否到位
  1030. lastRecord.OP60_ReinspectionImagePath = reinspectionImagePath; // 设备复检图片路径
  1031. lastRecord.OP60_TopCoverStatus = topCoverStatus; // 上盖板有无
  1032. lastRecord.OP60_TopCoverPressure = topCoverPressure; // 上盖板压合压力
  1033. try
  1034. {
  1035. db.Updateable(lastRecord)
  1036. .UpdateColumns(x => new {
  1037. x.OP60_AssemblyStatus,
  1038. x.OP60_ReinspectionImagePath,
  1039. x.OP60_TopCoverStatus,
  1040. x.OP60_TopCoverPressure
  1041. }).ExecuteCommand();
  1042. logNet.WriteError("OP60记录插入成功!");
  1043. return new ResponseMessage { result = true, text = "OP60记录插入成功!" };
  1044. }
  1045. catch (Exception ex)
  1046. {
  1047. logNet.WriteError("OP60记录插入出错!错误码:" + ex.Message);
  1048. return new ResponseMessage { result = false, text = "OP60记录插入出错!错误码:" + ex.Message };
  1049. }
  1050. }
  1051. // op701向testdata表格插入数据
  1052. public static ResponseMessage InsertOp701Data(string CarrierCode,string ProductBarcode, string torqueCurveDataPath,
  1053. float screwPressure, int turns, float lockTime, string lockOrder, string lockResult)
  1054. {
  1055. // 检查上一次插入的记录是否存在
  1056. var lastRecord = db.Queryable<TestData>()
  1057. .Where(x => x.CarrierCode == CarrierCode && x.ProductBarcode == ProductBarcode && x.OP60_AssemblyStatus != 2 && x.OP60_ReinspectionImagePath != "" &&
  1058. x.OP60_TopCoverStatus != 2 && x.OP60_TopCoverPressure != 0.0f) // 只查找有效插入的数据
  1059. .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  1060. .Take(1) // 只取一条记录
  1061. .First(); // 获取第一条记录,若没有则返回null
  1062. if (lastRecord == null)
  1063. {
  1064. logNet.WriteError("OP701错误:OP60插入的记录存在值为空!");
  1065. return new ResponseMessage { result = false, text = "OP701错误:OP60插入的记录存在值为空!" };
  1066. }
  1067. if (lastRecord.OP701_TorqueCurveDataPath != "" || lastRecord.OP701_ScrewPressure != 0.0f || lastRecord.OP701_Turns != 0 ||
  1068. lastRecord.OP701_LockTime != 0 || lastRecord.OP701_LockOrder != "" || lastRecord.OP701_LockResult != "")
  1069. {
  1070. logNet.WriteError("OP701错误:即将插入的数据存在值不为空,插入失败,请按标准操作!");
  1071. return new ResponseMessage { result = false, text = "OP701错误:即将插入的数据存在值不为空,插入失败,请按标准操作!" };
  1072. }
  1073. lastRecord.OP701_TorqueCurveDataPath = torqueCurveDataPath;
  1074. lastRecord.OP701_ScrewPressure = screwPressure;
  1075. lastRecord.OP701_Turns = turns;
  1076. lastRecord.OP701_LockTime = lockTime;
  1077. lastRecord.OP701_LockOrder = lockOrder;
  1078. lastRecord.OP701_LockResult = lockResult;
  1079. try
  1080. {
  1081. db.Updateable(lastRecord)
  1082. .UpdateColumns(x => new {
  1083. x.OP701_TorqueCurveDataPath,
  1084. x.OP701_ScrewPressure,
  1085. x.OP701_Turns,
  1086. x.OP701_LockTime,
  1087. x.OP701_LockOrder,
  1088. x.OP701_LockResult
  1089. }).ExecuteCommand();
  1090. logNet.WriteError("OP701记录插入成功!");
  1091. return new ResponseMessage { result = true, text = "OP701记录插入成功!" };
  1092. }
  1093. catch (Exception ex)
  1094. {
  1095. logNet.WriteError("OP701记录插入出错!错误码:" + ex.Message);
  1096. return new ResponseMessage { result = false, text = "OP701记录插入出错!错误码:" + ex.Message };
  1097. }
  1098. }
  1099. // op702向testdata表格插入数据
  1100. public static ResponseMessage InsertOp702Data(string CarrierCode,string ProductBarcode, string torqueCurveDataPath,
  1101. float screwPressure, int turns, float lockTime, string lockOrder, string lockResult)
  1102. {
  1103. // 检查上一次插入的记录是否存在
  1104. var lastRecord = db.Queryable<TestData>()
  1105. .Where(x => x.CarrierCode == CarrierCode && x.ProductBarcode == ProductBarcode && x.OP701_TorqueCurveDataPath != "" && x.OP701_ScrewPressure != 0.0f &&
  1106. x.OP701_Turns != 0 && x.OP701_LockTime != 0 && x.OP701_LockOrder != "" &&
  1107. x.OP701_LockResult != "") // 只查找有效插入的数据
  1108. .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  1109. .Take(1) // 只取一条记录
  1110. .First(); // 获取第一条记录,若没有则返回null
  1111. if (lastRecord == null)
  1112. {
  1113. logNet.WriteError("OP702错误:OP701插入的记录存在值为空!");
  1114. return new ResponseMessage { result = false, text = "OP702错误:OP701插入的记录存在值为空!" };
  1115. }
  1116. if (lastRecord.OP702_TorqueCurveDataPath != "" || lastRecord.OP702_ScrewPressure != 0.0f || lastRecord.OP702_Turns != 0 ||
  1117. lastRecord.OP702_LockTime != 0 || lastRecord.OP702_LockOrder != "" || lastRecord.OP702_LockResult != "")
  1118. {
  1119. logNet.WriteError("OP702错误:即将插入的数据存在值不为空,插入失败,请按标准操作!");
  1120. return new ResponseMessage { result = false, text = "OP702错误:即将插入的数据存在值不为空,插入失败,请按标准操作!" };
  1121. }
  1122. lastRecord.OP702_TorqueCurveDataPath = torqueCurveDataPath;
  1123. lastRecord.OP702_ScrewPressure = screwPressure;
  1124. lastRecord.OP702_Turns = turns;
  1125. lastRecord.OP702_LockTime = lockTime;
  1126. lastRecord.OP702_LockOrder = lockOrder;
  1127. lastRecord.OP702_LockResult = lockResult;
  1128. try
  1129. {
  1130. db.Updateable(lastRecord)
  1131. .UpdateColumns(x => new {
  1132. x.OP702_TorqueCurveDataPath,
  1133. x.OP702_ScrewPressure,
  1134. x.OP702_Turns,
  1135. x.OP702_LockTime,
  1136. x.OP702_LockOrder,
  1137. x.OP702_LockResult
  1138. }).ExecuteCommand();
  1139. logNet.WriteError("OP702记录插入成功!");
  1140. return new ResponseMessage { result = true, text = "OP702记录插入成功!" };
  1141. }
  1142. catch (Exception ex)
  1143. {
  1144. logNet.WriteError("OP702记录插入出错!错误码:" + ex.Message);
  1145. return new ResponseMessage { result = false, text = "OP702记录插入出错!错误码:" + ex.Message };
  1146. }
  1147. }
  1148. #region 实体
  1149. // 定义实体类(对应数据库表)载具绑定表
  1150. public class CarrierBind
  1151. {
  1152. // 主键ID,设置为自增且非空
  1153. [SqlSugar.SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
  1154. public int ID { get; set; } // 主键ID
  1155. // 其他列
  1156. public string CarrierCode { get; set; } = ""; // 载具码
  1157. public string ProductBarcode { get; set; } = ""; // 产品码
  1158. public DateTime CreateTime { get; set; } = DateTime.Now; // 创建时间
  1159. }
  1160. // 定义ProductBind实体类,表示表格结构
  1161. public class ProductBind
  1162. {
  1163. // 主键ID,设置为自增且非空
  1164. [SqlSugar.SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
  1165. public int ID { get; set; } // 主键ID
  1166. // 其他列
  1167. public DateTime CreateTime { get; set; } = DateTime.Now; // 创建时间
  1168. public string CarrierCode { get; set; } = ""; // 载具码
  1169. public string ProductBarcode { get; set; } = ""; // 产品条码
  1170. public string TopCover_Barcode { get; set; } = ""; // 上盖板条码
  1171. public string AddPCB_Barcode { get; set; } = ""; // ADD板条码
  1172. public int BindOrder { get; set; } = 0; // 绑定顺序
  1173. }
  1174. // 定义TestData实体类,表示表格TestData结构
  1175. public class TestData
  1176. {
  1177. // 主键ID,设置为自增且非空
  1178. [SqlSugar.SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
  1179. public int ID { get; set; } // 主键ID
  1180. // 其他列
  1181. public DateTime CreateTime { get; set; } = DateTime.Now; // 创建时间
  1182. public string CarrierCode { get; set; } = ""; // 载具码
  1183. public string ProductBarcode { get; set; } = ""; // 产品条码
  1184. public string TopCover_Barcode { get; set; } = ""; // 上盖板条码
  1185. public string AddPCB_Barcode { get; set; } = ""; // ADD板条码
  1186. public int BindOrder { get; set; } = 0; // 绑定顺序
  1187. //op10
  1188. public int OP10_ThrowingAmount { get; set; } = 0; // 抛料数量 // 清洗功率
  1189. public float OP10_CleaningPressure { get; set; } = 0.0f; // 清洗气压
  1190. public float OP10_CleaningSpeed { get; set; } = 0.0f; // 清洗速度
  1191. public float OP10_AirKnifeHeight { get; set; } = 0.0f; // 风刀高度
  1192. public float OP10_CleaningTime { get; set; } = 0.0f; // 清洗时间
  1193. public int OP10_CleaningCount { get; set; } = 0; // 清洗次数
  1194. public int OP10_RemainCount { get; set; } = 0; // 外壳体余料数
  1195. //op20
  1196. public int OP20_ThrowCount { get; set; } = 0; // 抛料数量
  1197. public int OP20_RemainCount { get; set; } = 0; // 上盖余料数
  1198. //op301
  1199. public float OP301_GluingSpeed { get; set; } = 0.0f; // 供胶速度
  1200. public float OP301_PressureAB { get; set; } = 0.0f; // A管气压
  1201. public float OP301_PressureDifferenceAB { get; set; } = 0.0f; // AB管气压差
  1202. public float OP301_ProductHeightInfo { get; set; } = 0.0f; // 产品测高信息
  1203. public float OP301_PeriodicWeightData { get; set; } = 0.0f; // 定期称重数据
  1204. public float OP301_RemainingGlueAmount { get; set; } = 0.0f; // 剩余胶量
  1205. //op302
  1206. public float OP302_GluingSpeed { get; set; } = 0.0f; // 供胶速度
  1207. public float OP302_PressureAB { get; set; } = 0.0f; // A管气压
  1208. public float OP302_PressureDifferenceAB { get; set; } = 0.0f; // AB管气压差
  1209. public float OP302_ProductHeightInfo { get; set; } = 0.0f; // 产品测高信息
  1210. public float OP302_PeriodicWeightData { get; set; } = 0.0f; // 定期称重数据
  1211. public float OP302_RemainingGlueAmount { get; set; } = 0.0f; // 剩余胶量
  1212. //op40
  1213. public float OP40_GluePosX { get; set; } = 0.0f; // 胶线位置X偏差
  1214. public float OP40_GluePosY { get; set; } = 0.0f; // 胶线位置Y偏差
  1215. public float OP40_GlueLineArea { get; set; } = 0.0f; // 胶线面积
  1216. public float OP40_GlueLineHeight { get; set; } = 0.0f; // 胶线高度
  1217. public int OP40_Result { get; set; } = 0; // 胶线检测结果 1:OK 非1:NG
  1218. public string OP40_InspectionImagePath { get; set; } = ""; // 检测图片路径
  1219. //op50
  1220. public int OP50_AssemblyStatus { get; set; } = 0; // 组装是否到位
  1221. public string OP50_ReinspectionImagePath { get; set; } = ""; // 设备复检图片路径
  1222. public int OP50_AddBoardStatus { get; set; } = 0; // ADD板有无
  1223. public int OP50_RemainCount { get; set; } = 0; // ADD板余料数
  1224. public float OP50_AddBoardPressure { get; set; } = 0.0f; // ADD板压合压力
  1225. //op60
  1226. public int OP60_AssemblyStatus { get; set; } = 0; // 组装是否到位
  1227. public int OP60_TopCoverStatus { get; set; } = 0; // 上盖板有无
  1228. public float OP60_TopCoverPressure { get; set; } = 0.0f; // 上盖板压合压力
  1229. public string OP60_ReinspectionImagePath { get; set; } = ""; // 设备复检图片路径
  1230. //op701
  1231. public string OP701_TorqueCurveDataPath { get; set; } = ""; // 扭力曲线数据表位置
  1232. public float OP701_ScrewPressure { get; set; } = 0.0f; // 螺丝压力
  1233. public int OP701_Turns { get; set; } = 0; // 圈数
  1234. public float OP701_LockTime { get; set; } = 0.0f; // 锁附时间
  1235. public string OP701_LockOrder { get; set; } = ""; // 锁附顺序
  1236. public string OP701_LockResult { get; set; } = ""; // 锁附结果
  1237. //op702
  1238. public string OP702_TorqueCurveDataPath { get; set; } = ""; // 扭力曲线数据表位置
  1239. public float OP702_ScrewPressure { get; set; } = 0.0f; // 螺丝压力
  1240. public int OP702_Turns { get; set; } = 0; // 圈数
  1241. public float OP702_LockTime { get; set; } = 0.0f; // 锁附时间
  1242. public string OP702_LockOrder { get; set; } = ""; // 锁附顺序
  1243. public string OP702_LockResult { get; set; } = ""; // 锁附结果
  1244. }
  1245. #endregion
  1246. #endregion
  1247. }
  1248. }