SQLHelper.cs 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  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(SqlSugarClient db, string carrierCode, string hydrocooling_Barcode, int bindOrder,
  600. int throwingAmount, float cleaningPower, float cleaningPressure, float cleaningSpeed,
  601. float airKnifeHeight, float cleaningTime, int cleaningCount)
  602. {
  603. #region 新建CarrierBind实体,并将数据插入carrierBind表格
  604. // 创建 CarrierBind 实体,并通过传入的参数设置字段值
  605. var CarrierBind_sumRecord = new CarrierBind
  606. {
  607. CarrierCode = carrierCode,
  608. ProductBarcode = hydrocooling_Barcode,
  609. };
  610. // 检查记录是否已经存在
  611. bool CarrierBind_exists = db.Queryable<CarrierBind>().Any(x => x.CarrierCode == CarrierBind_sumRecord.CarrierCode &&
  612. x.ProductBarcode == CarrierBind_sumRecord.ProductBarcode);
  613. if (CarrierBind_exists)
  614. {
  615. var maxBindOrder = db.Queryable<CarrierBind>()
  616. .Where(x => x.CarrierCode == CarrierBind_sumRecord.CarrierCode &&
  617. x.ProductBarcode == CarrierBind_sumRecord.ProductBarcode);
  618. db.Deleteable<CarrierBind>().Where(x => x.CarrierCode == carrierCode).ExecuteCommand();
  619. }
  620. else
  621. {
  622. // 插入数据
  623. try
  624. {
  625. db.Insertable(CarrierBind_sumRecord).ExecuteCommand();
  626. }
  627. catch (Exception ex)
  628. {
  629. return new ResponseMessage { result = true, text = "OP10数据-载具码与产品码绑定失败,错误码:" + ex.Message };
  630. }
  631. }
  632. #endregion
  633. #region 新建ProductBind实体,并将数据插入productBind表格
  634. // 创建 ProductBind 实体,并通过传入的参数设置字段值
  635. var ProductBind_sumRecord = new ProductBind
  636. {
  637. CarrierCode = carrierCode,//载具码
  638. ProductBarcode = hydrocooling_Barcode, // 水冷壳体条码
  639. BindOrder = bindOrder // 绑定顺序
  640. };
  641. // 检查记录是否已经存在
  642. bool ProductBind_exists = db.Queryable<ProductBind>().Any(x => x.CarrierCode == ProductBind_sumRecord.CarrierCode &&
  643. x.ProductBarcode == ProductBind_sumRecord.ProductBarcode &&
  644. x.BindOrder == ProductBind_sumRecord.BindOrder);
  645. if (ProductBind_exists)
  646. {
  647. }
  648. else
  649. {
  650. // 插入数据
  651. try
  652. {
  653. db.Insertable(ProductBind_sumRecord).ExecuteCommand();
  654. logNet.WriteError("OP10-数据插入到 productbind 表格成功!");
  655. }
  656. catch (Exception ex)
  657. {
  658. logNet.WriteError("OP10-数据插入到 productbind 表格出错!错误码:" + ex.Message);
  659. }
  660. }
  661. #endregion
  662. #region 将OP10数据插入testdata表格
  663. // 检查主键是否存在
  664. var existingRecord = db.Queryable<TestData>()
  665. .Where(x => x.CarrierCode == carrierCode && x.ProductBarcode == hydrocooling_Barcode && x.BindOrder == bindOrder)
  666. .First();
  667. if (existingRecord != null)
  668. {
  669. logNet.WriteError("OP10错误:数据已存在,载具码、水冷壳体码和绑定顺序相同!");
  670. return new ResponseMessage { result = false, text = "OP10错误:数据已存在,载具码、水冷壳体码和绑定顺序相同!" };
  671. }
  672. // 创建 Op10 实体,并通过传入的参数设置字段值
  673. var op10 = new TestData
  674. {
  675. CarrierCode = carrierCode, // 载具码
  676. ProductBarcode = hydrocooling_Barcode,// 水冷壳体码
  677. BindOrder = bindOrder, // 绑定顺序
  678. OP10_ThrowingAmount = throwingAmount, // 抛料数量
  679. OP10_CleaningPower = cleaningPower, // 清洗功率
  680. OP10_CleaningPressure = cleaningPressure, // 清洗气压
  681. OP10_CleaningSpeed = cleaningSpeed, // 清洗速度
  682. OP10_AirKnifeHeight = airKnifeHeight, // 风刀高度
  683. OP10_CleaningTime = cleaningTime, // 清洗时间
  684. OP10_CleaningCount = cleaningCount // 清洗次数
  685. };
  686. try
  687. {
  688. db.Insertable(op10).ExecuteCommand();
  689. logNet.WriteError("OP10记录插入成功!");
  690. return new ResponseMessage { result = true, text = "OP10记录插入成功"};
  691. }
  692. catch (Exception ex)
  693. {
  694. logNet.WriteError("OP10记录插入出错!错误码:" + ex.Message);
  695. return new ResponseMessage { result = false, text = "OP10记录插入出错!错误码:" + ex.Message };
  696. }
  697. #endregion
  698. }
  699. // op20向testdata表格插入数据
  700. public static ResponseMessage InsertOp20Data( int throwingAmount, string topCover_Barcode)
  701. {
  702. // 检查上一次插入的记录是否存在
  703. var lastRecord = db.Queryable<TestData>()
  704. .Where(x => x.OP10_ThrowingAmount != 0 &&
  705. x.OP10_CleaningPower != 0.0f &&
  706. x.OP10_CleaningPressure != 0.0f &&
  707. x.OP10_CleaningSpeed != 0.0f &&
  708. x.OP10_AirKnifeHeight != 0.0f &&
  709. x.OP10_CleaningTime != 0.0f &&
  710. x.OP10_CleaningCount != 0) // 只查找有效插入的数据
  711. .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  712. .Take(1) // 只取一条记录
  713. .First(); // 获取第一条记录,若没有则返回null
  714. if (lastRecord == null)
  715. {
  716. logNet.WriteError("OP20错误:OP10插入的记录存在值为空!");
  717. }
  718. if (lastRecord.OP20_ThrowingAmount != 0 || lastRecord.TopCover_Barcode != "")
  719. {
  720. logNet.WriteError("OP20错误:即将插入的数据存在值不为空,插入失败,请按标准操作!");
  721. }
  722. #region 往productBind表格中插入topCover_Barcode数据
  723. // 检查上一次插入的记录是否存在
  724. var productBind_lastRecord = db.Queryable<ProductBind>()
  725. .Where(x => x.CarrierCode != "" && x.ProductBarcode != "" && x.BindOrder != 0)
  726. .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  727. .Take(1) // 只取一条记录
  728. .First(); // 获取第一条记录,若没有则返回null
  729. if (productBind_lastRecord == null)
  730. {
  731. logNet.WriteError("OP20-错误:ProductBind表中最新插入的数据为空!");
  732. }
  733. if (productBind_lastRecord.TopCover_Barcode != "")
  734. {
  735. logNet.WriteError("OP20-错误:即将插入的数据存在值不为空,插入失败,请按标准操作!");
  736. }
  737. productBind_lastRecord.TopCover_Barcode = topCover_Barcode;
  738. try
  739. {
  740. db.Updateable(productBind_lastRecord)
  741. .UpdateColumns(x => new {
  742. x.TopCover_Barcode
  743. }).ExecuteCommand();
  744. logNet.WriteError("OP20往ProductBind表中插入TopCover_Barcode成功!");
  745. }
  746. catch (Exception ex)
  747. {
  748. logNet.WriteError("OP20往ProductBind表中插入TopCover_Barcode出错!错误码:" + ex.Message);
  749. }
  750. #endregion
  751. lastRecord.OP20_ThrowingAmount = throwingAmount;
  752. lastRecord.TopCover_Barcode = topCover_Barcode;
  753. try
  754. {
  755. db.Updateable(lastRecord)
  756. .UpdateColumns(x => new { x.OP20_ThrowingAmount, x.TopCover_Barcode })
  757. .ExecuteCommand();
  758. logNet.WriteError("OP20记录插入成功!");
  759. return new ResponseMessage { result = false, text = "OP20记录插入成功!" };
  760. }
  761. catch (Exception ex)
  762. {
  763. logNet.WriteError("OP20记录插入出错!错误码:" + ex.Message);
  764. return new ResponseMessage { result = false, text = "OP20记录插入出错!错误码:" + ex.Message };
  765. }
  766. }
  767. // op301向testdata表格插入数据
  768. public static ResponseMessage InsertOp301Data( float gluingSpeed, float pressureA, float pressureB, float pressureDifferenceAB,
  769. float productHeightInfo, float periodicWeightData, float remainingGlueAmount)
  770. {
  771. // 检查上一次插入的记录是否存在
  772. var lastRecord = db.Queryable<TestData>()
  773. .Where(x => x.OP20_ThrowingAmount != 0 && x.TopCover_Barcode != "") // 只查找有效插入的数据
  774. .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  775. .Take(1) // 只取一条记录
  776. .First(); // 获取第一条记录,若没有则返回null
  777. if (lastRecord == null)
  778. {
  779. logNet.WriteError("OP301错误:OP20插入的记录存在值为空!");
  780. return new ResponseMessage { result = false, text = "OP301错误:OP20插入的记录存在值为空!" };
  781. }
  782. if (lastRecord.OP301_GluingSpeed != 0.0f || lastRecord.OP301_PressureA != 0.0f || lastRecord.OP301_PressureB != 0.0f ||
  783. lastRecord.OP301_PressureDifferenceAB != 0.0f || lastRecord.OP301_ProductHeightInfo != 0.0f ||
  784. lastRecord.OP301_PeriodicWeightData != 0.0f || lastRecord.OP301_RemainingGlueAmount != 0.0f)
  785. {
  786. logNet.WriteError("OP301错误:即将插入的数据存在值不为空,插入失败,请按标准操作!");
  787. return new ResponseMessage { result = false, text = "OP301错误:即将插入的数据存在值不为空,插入失败,请按标准操作!" };
  788. }
  789. lastRecord.OP301_GluingSpeed = gluingSpeed; // 供胶速度
  790. lastRecord.OP301_PressureA = pressureA; // A管气压
  791. lastRecord.OP301_PressureB = pressureB; // B管气压
  792. lastRecord.OP301_PressureDifferenceAB = pressureDifferenceAB; // AB管气压差
  793. lastRecord.OP301_ProductHeightInfo = productHeightInfo; // 产品测高信息
  794. lastRecord.OP301_PeriodicWeightData = periodicWeightData; // 定期称重数据
  795. lastRecord.OP301_RemainingGlueAmount = remainingGlueAmount; // 剩余胶量
  796. try
  797. {
  798. db.Updateable(lastRecord)
  799. .UpdateColumns(x => new {
  800. x.OP301_GluingSpeed,
  801. x.OP301_PressureA,
  802. x.OP301_PressureB,
  803. x.OP301_PressureDifferenceAB,
  804. x.OP301_ProductHeightInfo,
  805. x.OP301_PeriodicWeightData,
  806. x.OP301_RemainingGlueAmount
  807. }).ExecuteCommand();
  808. logNet.WriteError("OP301记录插入成功!");
  809. return new ResponseMessage { result = true, text = "OP301记录插入成功"};
  810. }
  811. catch (Exception ex)
  812. {
  813. logNet.WriteError("OP301记录插入出错!错误码:" + ex.Message);
  814. return new ResponseMessage { result = false, text = "OP301记录插入出错!错误码:" + ex.Message };
  815. }
  816. }
  817. // op302向testdata表格插入数据
  818. public static ResponseMessage InsertOp302Data( float gluingSpeed, float pressureA, float pressureB, float pressureDifferenceAB,
  819. float productHeightInfo, float periodicWeightData, float remainingGlueAmount)
  820. {
  821. // 检查上一次插入的记录是否存在
  822. var lastRecord = db.Queryable<TestData>()
  823. .Where(x => x.OP301_GluingSpeed != 0.0f && x.OP301_PressureA != 0.0f && x.OP301_PressureB != 0.0f &&
  824. x.OP301_PressureDifferenceAB != 0.0f && x.OP301_ProductHeightInfo != 0.0f &&
  825. x.OP301_PeriodicWeightData != 0.0f && x.OP301_RemainingGlueAmount != 0.0f) // 只查找有效插入的数据
  826. .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  827. .Take(1) // 只取一条记录
  828. .First(); // 获取第一条记录,若没有则返回null
  829. if (lastRecord == null)
  830. {
  831. logNet.WriteError("OP302错误:OP301插入的记录存在值为空!");
  832. return new ResponseMessage { result = false, text = "OP302错误:OP301插入的记录存在值为空!" };
  833. }
  834. if (lastRecord.OP302_GluingSpeed != 0.0f || lastRecord.OP302_PressureA != 0.0f || lastRecord.OP302_PressureB != 0.0f ||
  835. lastRecord.OP302_PressureDifferenceAB != 0.0f || lastRecord.OP302_ProductHeightInfo != 0.0f ||
  836. lastRecord.OP302_PeriodicWeightData != 0.0f || lastRecord.OP302_RemainingGlueAmount != 0.0f)
  837. {
  838. logNet.WriteError("OP302错误:即将插入的数据存在值不为空,插入失败,请按标准操作!");
  839. return new ResponseMessage { result = false, text = "OP302错误:即将插入的数据存在值不为空,插入失败,请按标准操作!" };
  840. }
  841. lastRecord.OP302_GluingSpeed = gluingSpeed; // 供胶速度
  842. lastRecord.OP302_PressureA = pressureA; // A管气压
  843. lastRecord.OP302_PressureB = pressureB; // B管气压
  844. lastRecord.OP302_PressureDifferenceAB = pressureDifferenceAB; // AB管气压差
  845. lastRecord.OP302_ProductHeightInfo = productHeightInfo; // 产品测高信息
  846. lastRecord.OP302_PeriodicWeightData = periodicWeightData; // 定期称重数据
  847. lastRecord.OP302_RemainingGlueAmount = remainingGlueAmount; // 剩余胶量
  848. try
  849. {
  850. db.Updateable(lastRecord)
  851. .UpdateColumns(x => new {
  852. x.OP302_GluingSpeed,
  853. x.OP302_PressureA,
  854. x.OP302_PressureB,
  855. x.OP302_PressureDifferenceAB,
  856. x.OP302_ProductHeightInfo,
  857. x.OP302_PeriodicWeightData,
  858. x.OP302_RemainingGlueAmount
  859. }).ExecuteCommand();
  860. logNet.WriteError("OP302记录插入成功!");
  861. return new ResponseMessage { result = true, text = "OP302记录插入成功" };
  862. }
  863. catch (Exception ex)
  864. {
  865. logNet.WriteError("OP302记录插入出错!错误码:" + ex.Message);
  866. return new ResponseMessage { result = false, text = "OP302错误:即将插入的数据存在值不为空,插入失败,请按标准操作!" };
  867. }
  868. }
  869. // op40向testdata表格插入数据
  870. public static ResponseMessage InsertOp40Data( string gluePosition, float glueLineArea,
  871. float glueLineHeight, string inspectionImagePath)
  872. {
  873. // 检查上一次插入的记录是否存在
  874. var lastRecord = db.Queryable<TestData>()
  875. .Where(x => x.OP302_GluingSpeed != 0.0f && x.OP302_PressureA != 0.0f && x.OP302_PressureB != 0.0f &&
  876. x.OP302_PressureDifferenceAB != 0.0f && x.OP302_ProductHeightInfo != 0.0f &&
  877. x.OP302_PeriodicWeightData != 0.0f && x.OP302_RemainingGlueAmount != 0.0f) // 只查找有效插入的数据
  878. .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  879. .Take(1) // 只取一条记录
  880. .First(); // 获取第一条记录,若没有则返回null
  881. if (lastRecord == null)
  882. {
  883. logNet.WriteError("OP40错误:OP302插入的记录存在值为空!");
  884. return new ResponseMessage { result = false, text = "OP40错误:OP302插入的记录存在值为空!" };
  885. }
  886. if (lastRecord.OP40_GluePosition != "" || lastRecord.OP40_GlueLineArea != 0.0f ||
  887. lastRecord.OP40_GlueLineHeight != 0.0f || lastRecord.OP40_InspectionImagePath != "")
  888. {
  889. logNet.WriteError("OP40错误:即将插入的数据存在值不为空,插入失败,请按标准操作!");
  890. return new ResponseMessage { result = false, text = "OP40错误:即将插入的数据存在值不为空,插入失败,请按标准操作!" };
  891. }
  892. lastRecord.OP40_GluePosition = gluePosition; // 点胶位置
  893. lastRecord.OP40_GlueLineArea = glueLineArea; // 胶线面积
  894. lastRecord.OP40_GlueLineHeight = glueLineHeight; // 胶线高度
  895. lastRecord.OP40_InspectionImagePath = inspectionImagePath; // 检测图片路径
  896. try
  897. {
  898. db.Updateable(lastRecord)
  899. .UpdateColumns(x => new {
  900. x.OP40_GluePosition,
  901. x.OP40_GlueLineArea,
  902. x.OP40_GlueLineHeight,
  903. x.OP40_InspectionImagePath
  904. }).ExecuteCommand();
  905. logNet.WriteError("OP40记录插入成功!");
  906. return new ResponseMessage { result = true, text = "OP40记录插入成功!" };
  907. }
  908. catch (Exception ex)
  909. {
  910. logNet.WriteError("OP40记录插入出错!错误码:" + ex.Message);
  911. return new ResponseMessage { result = true, text = "OP40记录插入出错!错误码:" + ex.Message };
  912. }
  913. }
  914. //OP50 往product塞数据
  915. public static ResponseMessage InsertOp50Product( string CarrierCode,string ProductBarcode, string addPCB_Barcode)
  916. {
  917. #region 往productBind表格中插入addPCB_Barcode数据
  918. // 检查上一次插入的记录是否存在
  919. var productBind_lastRecord = db.Queryable<ProductBind>()
  920. .Where(x => x.CarrierCode == CarrierCode && x.ProductBarcode == ProductBarcode && x.BindOrder != 0)
  921. .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  922. .Take(1) // 只取一条记录
  923. .First(); // 获取第一条记录,若没有则返回null
  924. if (productBind_lastRecord == null)
  925. {
  926. logNet.WriteError("OP50-错误:ProductBind表数据为空!");
  927. return new ResponseMessage { result = false, text = "OP50-错误:ProductBind表数据为空!" };
  928. }
  929. if (productBind_lastRecord.AddPCB_Barcode != "")
  930. {
  931. logNet.WriteError("OP50-错误:即将插入ProductBind的数据存在值不为空,插入失败,请按标准操作!");
  932. return new ResponseMessage { result = false, text = "OP50-错误:即将插入ProductBind的数据存在值不为空,插入失败,请按标准操作!" };
  933. }
  934. productBind_lastRecord.AddPCB_Barcode = addPCB_Barcode;
  935. try
  936. {
  937. db.Updateable(productBind_lastRecord)
  938. .UpdateColumns(x => new {
  939. x.AddPCB_Barcode
  940. }).ExecuteCommand();
  941. logNet.WriteError("OP50往ProductBind表中插入AddPCB_Barcode成功!");
  942. return new ResponseMessage { result = false, text = "OP50往ProductBind表中插入AddPCB_Barcode成功!" };
  943. }
  944. catch (Exception ex)
  945. {
  946. logNet.WriteError("OP50往ProductBind表中插入AddPCB_Barcode出错!错误码:" + ex.Message);
  947. return new ResponseMessage { result = false, text = "OP50往ProductBind表中插入AddPCB_Barcode出错!错误码:" + ex.Message };
  948. }
  949. #endregion
  950. }
  951. // op50向testdata表格插入数据
  952. public static ResponseMessage InsertOp50Data(string CarrierCode,string ProductBarcode,string addPCB_Barcode, int assemblyStatus,
  953. string reinspectionImagePath, int addBoardStatus, float addBoardPressure)
  954. {
  955. // 检查上一次插入的记录是否存在
  956. var lastRecord = db.Queryable<TestData>()
  957. .Where(x => x.CarrierCode == CarrierCode && x.ProductBarcode == ProductBarcode && x.OP40_GluePosition != "" && x.OP40_GlueLineArea != 0.0f &&
  958. x.OP40_GlueLineHeight != 0.0f && x.OP40_InspectionImagePath != "") // 只查找有效插入的数据
  959. .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  960. .Take(1) // 只取一条记录
  961. .First(); // 获取第一条记录,若没有则返回null
  962. if (lastRecord == null)
  963. {
  964. logNet.WriteError("OP50错误:OP40插入的记录存在值为空!");
  965. return new ResponseMessage { result = false, text = "OP50错误:OP40插入的记录存在值为空!!" };
  966. }
  967. if (lastRecord.AddPCB_Barcode != "" || lastRecord.OP50_AssemblyStatus != 2 || lastRecord.OP50_ReinspectionImagePath != "" ||
  968. lastRecord.OP50_AddBoardStatus != 2 || lastRecord.OP50_AddBoardPressure != 0.0f)
  969. {
  970. logNet.WriteError("OP50错误:即将插入的数据存在值不为空,插入失败,请按标准操作!");
  971. return new ResponseMessage { result = false, text = "OP50错误:即将插入的数据存在值不为空,插入失败,请按标准操作!" };
  972. }
  973. lastRecord.AddPCB_Barcode = addPCB_Barcode;
  974. lastRecord.OP50_AssemblyStatus = assemblyStatus; // 组装是否到位
  975. lastRecord.OP50_ReinspectionImagePath = reinspectionImagePath; // 设备复检图片路径
  976. lastRecord.OP50_AddBoardStatus = addBoardStatus; // ADD板有无
  977. lastRecord.OP50_AddBoardPressure = addBoardPressure; // ADD板压合压力
  978. try
  979. {
  980. db.Updateable(lastRecord)
  981. .UpdateColumns(x => new {
  982. x.AddPCB_Barcode,
  983. x.OP50_AssemblyStatus,
  984. x.OP50_ReinspectionImagePath,
  985. x.OP50_AddBoardStatus,
  986. x.OP50_AddBoardPressure
  987. }).ExecuteCommand();
  988. logNet.WriteError("OP50记录插入成功!");
  989. return new ResponseMessage { result = true, text = "OP50记录插入成功!" };
  990. }
  991. catch (Exception ex)
  992. {
  993. logNet.WriteError("OP50记录插入出错!错误码:" + ex.Message);
  994. return new ResponseMessage { result = false, text = "OP50记录插入出错!错误码:" + ex.Message };
  995. }
  996. }
  997. // op60向testdata表格插入数据
  998. public static ResponseMessage InsertOp60Data(string CarrierCode,string ProductBarcode, int assemblyStatus, string reinspectionImagePath,
  999. int topCoverStatus, float topCoverPressure)
  1000. {
  1001. // 检查上一次插入的记录是否存在
  1002. var lastRecord = db.Queryable<TestData>()
  1003. .Where(x => x.CarrierCode == CarrierCode && x.ProductBarcode == ProductBarcode && x.AddPCB_Barcode != "" && x.OP50_AssemblyStatus != 2 && x.OP50_ReinspectionImagePath != "" &&
  1004. x.OP50_AddBoardStatus != 2 && x.OP50_AddBoardPressure != 0.0f) // 只查找有效插入的数据
  1005. .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  1006. .Take(1) // 只取一条记录
  1007. .First(); // 获取第一条记录,若没有则返回null
  1008. if (lastRecord == null)
  1009. {
  1010. logNet.WriteError("OP60错误:OP50插入的记录存在值为空!");
  1011. return new ResponseMessage { result = false, text = "OP60错误:OP50插入的记录存在值为空!" };
  1012. }
  1013. if (lastRecord.OP60_AssemblyStatus != 2 || lastRecord.OP60_ReinspectionImagePath != "" ||
  1014. lastRecord.OP60_TopCoverStatus != 2 || lastRecord.OP60_TopCoverPressure != 0.0f)
  1015. {
  1016. logNet.WriteError("OP60错误:即将插入的数据存在值不为空,插入失败,请按标准操作!");
  1017. return new ResponseMessage { result = false, text = "OP60错误:即将插入的数据存在值不为空,插入失败,请按标准操作!" };
  1018. }
  1019. lastRecord.OP60_AssemblyStatus = assemblyStatus; // 组装是否到位
  1020. lastRecord.OP60_ReinspectionImagePath = reinspectionImagePath; // 设备复检图片路径
  1021. lastRecord.OP60_TopCoverStatus = topCoverStatus; // 上盖板有无
  1022. lastRecord.OP60_TopCoverPressure = topCoverPressure; // 上盖板压合压力
  1023. try
  1024. {
  1025. db.Updateable(lastRecord)
  1026. .UpdateColumns(x => new {
  1027. x.OP60_AssemblyStatus,
  1028. x.OP60_ReinspectionImagePath,
  1029. x.OP60_TopCoverStatus,
  1030. x.OP60_TopCoverPressure
  1031. }).ExecuteCommand();
  1032. logNet.WriteError("OP60记录插入成功!");
  1033. return new ResponseMessage { result = true, text = "OP60记录插入成功!" };
  1034. }
  1035. catch (Exception ex)
  1036. {
  1037. logNet.WriteError("OP60记录插入出错!错误码:" + ex.Message);
  1038. return new ResponseMessage { result = false, text = "OP60记录插入出错!错误码:" + ex.Message };
  1039. }
  1040. }
  1041. // op701向testdata表格插入数据
  1042. public static ResponseMessage InsertOp701Data(string CarrierCode,string ProductBarcode, string torqueCurveDataPath,
  1043. float screwPressure, int turns, float lockTime, string lockOrder, string lockResult)
  1044. {
  1045. // 检查上一次插入的记录是否存在
  1046. var lastRecord = db.Queryable<TestData>()
  1047. .Where(x => x.CarrierCode == CarrierCode && x.ProductBarcode == ProductBarcode && x.OP60_AssemblyStatus != 2 && x.OP60_ReinspectionImagePath != "" &&
  1048. x.OP60_TopCoverStatus != 2 && x.OP60_TopCoverPressure != 0.0f) // 只查找有效插入的数据
  1049. .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  1050. .Take(1) // 只取一条记录
  1051. .First(); // 获取第一条记录,若没有则返回null
  1052. if (lastRecord == null)
  1053. {
  1054. logNet.WriteError("OP701错误:OP60插入的记录存在值为空!");
  1055. return new ResponseMessage { result = false, text = "OP701错误:OP60插入的记录存在值为空!" };
  1056. }
  1057. if (lastRecord.OP701_TorqueCurveDataPath != "" || lastRecord.OP701_ScrewPressure != 0.0f || lastRecord.OP701_Turns != 0 ||
  1058. lastRecord.OP701_LockTime != 0 || lastRecord.OP701_LockOrder != "" || lastRecord.OP701_LockResult != "")
  1059. {
  1060. logNet.WriteError("OP701错误:即将插入的数据存在值不为空,插入失败,请按标准操作!");
  1061. return new ResponseMessage { result = false, text = "OP701错误:即将插入的数据存在值不为空,插入失败,请按标准操作!" };
  1062. }
  1063. lastRecord.OP701_TorqueCurveDataPath = torqueCurveDataPath;
  1064. lastRecord.OP701_ScrewPressure = screwPressure;
  1065. lastRecord.OP701_Turns = turns;
  1066. lastRecord.OP701_LockTime = lockTime;
  1067. lastRecord.OP701_LockOrder = lockOrder;
  1068. lastRecord.OP701_LockResult = lockResult;
  1069. try
  1070. {
  1071. db.Updateable(lastRecord)
  1072. .UpdateColumns(x => new {
  1073. x.OP701_TorqueCurveDataPath,
  1074. x.OP701_ScrewPressure,
  1075. x.OP701_Turns,
  1076. x.OP701_LockTime,
  1077. x.OP701_LockOrder,
  1078. x.OP701_LockResult
  1079. }).ExecuteCommand();
  1080. logNet.WriteError("OP701记录插入成功!");
  1081. return new ResponseMessage { result = true, text = "OP701记录插入成功!" };
  1082. }
  1083. catch (Exception ex)
  1084. {
  1085. logNet.WriteError("OP701记录插入出错!错误码:" + ex.Message);
  1086. return new ResponseMessage { result = false, text = "OP701记录插入出错!错误码:" + ex.Message };
  1087. }
  1088. }
  1089. // op702向testdata表格插入数据
  1090. public static ResponseMessage InsertOp702Data(string CarrierCode,string ProductBarcode, string torqueCurveDataPath,
  1091. float screwPressure, int turns, float lockTime, string lockOrder, string lockResult)
  1092. {
  1093. // 检查上一次插入的记录是否存在
  1094. var lastRecord = db.Queryable<TestData>()
  1095. .Where(x => x.CarrierCode == CarrierCode && x.ProductBarcode == ProductBarcode && x.OP701_TorqueCurveDataPath != "" && x.OP701_ScrewPressure != 0.0f &&
  1096. x.OP701_Turns != 0 && x.OP701_LockTime != 0 && x.OP701_LockOrder != "" &&
  1097. x.OP701_LockResult != "") // 只查找有效插入的数据
  1098. .OrderBy(x => x.ID, OrderByType.Desc) // 按照ID降序查找最新记录
  1099. .Take(1) // 只取一条记录
  1100. .First(); // 获取第一条记录,若没有则返回null
  1101. if (lastRecord == null)
  1102. {
  1103. logNet.WriteError("OP702错误:OP701插入的记录存在值为空!");
  1104. return new ResponseMessage { result = false, text = "OP702错误:OP701插入的记录存在值为空!" };
  1105. }
  1106. if (lastRecord.OP702_TorqueCurveDataPath != "" || lastRecord.OP702_ScrewPressure != 0.0f || lastRecord.OP702_Turns != 0 ||
  1107. lastRecord.OP702_LockTime != 0 || lastRecord.OP702_LockOrder != "" || lastRecord.OP702_LockResult != "")
  1108. {
  1109. logNet.WriteError("OP702错误:即将插入的数据存在值不为空,插入失败,请按标准操作!");
  1110. return new ResponseMessage { result = false, text = "OP702错误:即将插入的数据存在值不为空,插入失败,请按标准操作!" };
  1111. }
  1112. lastRecord.OP702_TorqueCurveDataPath = torqueCurveDataPath;
  1113. lastRecord.OP702_ScrewPressure = screwPressure;
  1114. lastRecord.OP702_Turns = turns;
  1115. lastRecord.OP702_LockTime = lockTime;
  1116. lastRecord.OP702_LockOrder = lockOrder;
  1117. lastRecord.OP702_LockResult = lockResult;
  1118. try
  1119. {
  1120. db.Updateable(lastRecord)
  1121. .UpdateColumns(x => new {
  1122. x.OP702_TorqueCurveDataPath,
  1123. x.OP702_ScrewPressure,
  1124. x.OP702_Turns,
  1125. x.OP702_LockTime,
  1126. x.OP702_LockOrder,
  1127. x.OP702_LockResult
  1128. }).ExecuteCommand();
  1129. logNet.WriteError("OP702记录插入成功!");
  1130. return new ResponseMessage { result = true, text = "OP702记录插入成功!" };
  1131. }
  1132. catch (Exception ex)
  1133. {
  1134. logNet.WriteError("OP702记录插入出错!错误码:" + ex.Message);
  1135. return new ResponseMessage { result = false, text = "OP702记录插入出错!错误码:" + ex.Message };
  1136. }
  1137. }
  1138. #region 实体
  1139. // 定义实体类(对应数据库表)载具绑定表
  1140. public class CarrierBind
  1141. {
  1142. // 主键ID,设置为自增且非空
  1143. [SqlSugar.SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
  1144. public int ID { get; set; } // 主键ID
  1145. // 其他列
  1146. public string CarrierCode { get; set; } = ""; // 载具码
  1147. public string ProductBarcode { get; set; } = ""; // 产品码
  1148. public DateTime CreateTime { get; set; } = DateTime.Now; // 创建时间
  1149. }
  1150. // 定义ProductBind实体类,表示表格结构
  1151. public class ProductBind
  1152. {
  1153. // 主键ID,设置为自增且非空
  1154. [SqlSugar.SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
  1155. public int ID { get; set; } // 主键ID
  1156. // 其他列
  1157. public DateTime CreateTime { get; set; } = DateTime.Now; // 创建时间
  1158. public string CarrierCode { get; set; } = ""; // 载具码
  1159. public string ProductBarcode { get; set; } = ""; // 产品条码
  1160. public string TopCover_Barcode { get; set; } = ""; // 上盖板条码
  1161. public string AddPCB_Barcode { get; set; } = ""; // ADD板条码
  1162. public int BindOrder { get; set; } = 0; // 绑定顺序
  1163. }
  1164. // 定义TestData实体类,表示表格TestData结构
  1165. public class TestData
  1166. {
  1167. // 主键ID,设置为自增且非空
  1168. [SqlSugar.SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
  1169. public int ID { get; set; } // 主键ID
  1170. // 其他列
  1171. public DateTime CreateTime { get; set; } = DateTime.Now; // 创建时间
  1172. public string CarrierCode { get; set; } = ""; // 载具码
  1173. public string ProductBarcode { get; set; } = ""; // 产品条码
  1174. public string TopCover_Barcode { get; set; } = ""; // 上盖板条码
  1175. public string AddPCB_Barcode { get; set; } = ""; // ADD板条码
  1176. public int BindOrder { get; set; } = 0; // 绑定顺序
  1177. //op10
  1178. public int OP10_ThrowingAmount { get; set; } = 0; // 抛料数量
  1179. public float OP10_CleaningPower { get; set; } = 0.0f; // 清洗功率
  1180. public float OP10_CleaningPressure { get; set; } = 0.0f; // 清洗气压
  1181. public float OP10_CleaningSpeed { get; set; } = 0.0f; // 清洗速度
  1182. public float OP10_AirKnifeHeight { get; set; } = 0.0f; // 风刀高度
  1183. public float OP10_CleaningTime { get; set; } = 0.0f; // 清洗时间
  1184. public int OP10_CleaningCount { get; set; } = 0; // 清洗次数
  1185. //op20
  1186. public int OP20_ThrowingAmount { get; set; } = 0; // 抛料数量
  1187. //op301
  1188. public float OP301_GluingSpeed { get; set; } = 0.0f; // 供胶速度
  1189. public float OP301_PressureA { get; set; } = 0.0f; // A管气压
  1190. public float OP301_PressureB { get; set; } = 0.0f; // B管气压
  1191. public float OP301_PressureDifferenceAB { get; set; } = 0.0f; // AB管气压差
  1192. public float OP301_ProductHeightInfo { get; set; } = 0.0f; // 产品测高信息
  1193. public float OP301_PeriodicWeightData { get; set; } = 0.0f; // 定期称重数据
  1194. public float OP301_RemainingGlueAmount { get; set; } = 0.0f; // 剩余胶量
  1195. //op302
  1196. public float OP302_GluingSpeed { get; set; } = 0.0f; // 供胶速度
  1197. public float OP302_PressureA { get; set; } = 0.0f; // A管气压
  1198. public float OP302_PressureB { get; set; } = 0.0f; // B管气压
  1199. public float OP302_PressureDifferenceAB { get; set; } = 0.0f; // AB管气压差
  1200. public float OP302_ProductHeightInfo { get; set; } = 0.0f; // 产品测高信息
  1201. public float OP302_PeriodicWeightData { get; set; } = 0.0f; // 定期称重数据
  1202. public float OP302_RemainingGlueAmount { get; set; } = 0.0f; // 剩余胶量
  1203. //op40
  1204. public string OP40_GluePosition { get; set; } = ""; // 点胶位置
  1205. public float OP40_GlueLineArea { get; set; } = 0.0f; // 胶线面积
  1206. public float OP40_GlueLineHeight { get; set; } = 0.0f; // 胶线高度
  1207. public string OP40_InspectionImagePath { get; set; } = ""; // 检测图片路径
  1208. //op50
  1209. public int OP50_AssemblyStatus { get; set; } = 2; // 组装是否到位
  1210. public string OP50_ReinspectionImagePath { get; set; } = ""; // 设备复检图片路径
  1211. public int OP50_AddBoardStatus { get; set; } = 2; // ADD板有无
  1212. public float OP50_AddBoardPressure { get; set; } = 0.0f; // ADD板压合压力
  1213. //op60
  1214. public int OP60_AssemblyStatus { get; set; } = 2; // 组装是否到位
  1215. public string OP60_ReinspectionImagePath { get; set; } = ""; // 设备复检图片路径
  1216. public int OP60_TopCoverStatus { get; set; } = 2; // 上盖板有无
  1217. public float OP60_TopCoverPressure { get; set; } = 0.0f; // 上盖板压合压力
  1218. //op701
  1219. public string OP701_TorqueCurveDataPath { get; set; } = ""; // 扭力曲线数据表位置
  1220. public float OP701_ScrewPressure { get; set; } = 0.0f; // 螺丝压力
  1221. public int OP701_Turns { get; set; } = 0; // 圈数
  1222. public float OP701_LockTime { get; set; } = 0.0f; // 锁附时间
  1223. public string OP701_LockOrder { get; set; } = ""; // 锁附顺序
  1224. public string OP701_LockResult { get; set; } = ""; // 锁附结果
  1225. //op702
  1226. public string OP702_TorqueCurveDataPath { get; set; } = ""; // 扭力曲线数据表位置
  1227. public float OP702_ScrewPressure { get; set; } = 0.0f; // 螺丝压力
  1228. public int OP702_Turns { get; set; } = 0; // 圈数
  1229. public float OP702_LockTime { get; set; } = 0.0f; // 锁附时间
  1230. public string OP702_LockOrder { get; set; } = ""; // 锁附顺序
  1231. public string OP702_LockResult { get; set; } = ""; // 锁附结果
  1232. }
  1233. #endregion
  1234. #endregion
  1235. }
  1236. }