DatabaseHelper.cs 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.SQLite;
  4. using System.Data;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using TeamAAS_VP;
  9. using System.IO;
  10. using System.Windows;
  11. using System.Runtime.CompilerServices;
  12. using TeamAAS_VP.Models;
  13. using System.Web.UI.WebControls;
  14. using TeamAAS_VP.Enums;
  15. using System.Windows.Shapes;
  16. using TeamAAS_VP.Core;
  17. using NPOI.Util;
  18. using NPOI.SS.Formula.Functions;
  19. using TouchSocket.Core;
  20. using System.Runtime.Remoting.Contexts;
  21. using TeamAAS_VP.Views.Product;
  22. using System.Windows.Documents;
  23. using System.Runtime.InteropServices.ComTypes;
  24. using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
  25. using NPOI.SS.UserModel;
  26. using Cognex.VisionPro.ToolBlock;
  27. using Org.BouncyCastle.Asn1.X509.Qualified;
  28. namespace TeamAAS_VP.Data
  29. {
  30. public class DatabaseHelper
  31. {
  32. /// <summary>
  33. /// 初始化数据库
  34. /// </summary>
  35. /// <returns></returns>
  36. public static bool InitDatabase()
  37. {
  38. try
  39. {
  40. //判断数据库文件是否存在,如若不存在,则创建默认数据库
  41. //用户数据库
  42. if (!File.Exists(FilePath.UserDbPath))
  43. {
  44. if (!Directory.Exists(System.IO.Path.GetDirectoryName(FilePath.UserDbPath)))
  45. {
  46. Directory.CreateDirectory(System.IO.Path.GetDirectoryName(FilePath.UserDbPath));
  47. }
  48. //如果数据库文件不存在,则创建一个数据库
  49. SQLiteConnection.CreateFile(FilePath.UserDbPath);
  50. }
  51. if (!IsHaveTable("Users", FilePath.UserDbPath))
  52. {
  53. CreateTable("Users", "(UserName TEXT,UserPassword TEXT,UserPart TEXT,AddTime DATETIME,IsRemember BOOL)", FilePath.UserDbPath);
  54. string cmd = $"insert into Users(UserName,UserPassword,UserPart,AddTime,IsRemember) values('操作员','','Operator','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}',False)";
  55. WriteCommandToDatabase(cmd, FilePath.UserDbPath);
  56. cmd = $"insert into Users(UserName,UserPassword,UserPart,AddTime,IsRemember) values('工程师','123','Engineer','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}',False)";
  57. WriteCommandToDatabase(cmd, FilePath.UserDbPath);
  58. cmd = $"insert into Users(UserName,UserPassword,UserPart,AddTime,IsRemember) values('管理员','team123456','Administrator','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}',False)";
  59. WriteCommandToDatabase(cmd, FilePath.UserDbPath);
  60. }
  61. //生产记录数据库
  62. if (!File.Exists(FilePath.ProductionRecordsDbPath))
  63. {
  64. //如果数据库文件不存在,则创建一个数据库
  65. SQLiteConnection.CreateFile(FilePath.ProductionRecordsDbPath);
  66. }
  67. //报警记录
  68. if (!IsHaveTable("Alarm", FilePath.ProductionRecordsDbPath))
  69. {
  70. CreateTable("Alarm", "(Time DATETIME,ErrorCode TEXT,ErrorMessage TEXT,Countermeasure TEXT)", FilePath.ProductionRecordsDbPath);
  71. }
  72. //软件操作记录
  73. if (!IsHaveTable("OperationLog", FilePath.ProductionRecordsDbPath))
  74. {
  75. CreateTable("OperationLog", "(Time DATETIME,UserName TEXT,UserPart TEXT,Content TEXT)", FilePath.ProductionRecordsDbPath);
  76. }
  77. ////生产记录
  78. //if (!IsHaveTable("ProductionRecords", FilePath.ProductionRecordsDbPath))
  79. //{
  80. // CreateTable("ProductionRecords", "(Time DATETIME,Content TEXT)", FilePath.ProductionRecordsDbPath);
  81. //}
  82. ////视觉拍照记录
  83. //if (!IsHaveTable("CameraRecords", FilePath.ProductionRecordsDbPath))
  84. //{
  85. // CreateTable("CameraRecords", "(Time DATETIME,ProductName TEXT,ProductSN TEXT,CameraName TEXT,ProcessName TEXT,Result TEXT,ResultContent TEXT,ProcessingTime DOUBLE)", FilePath.ProductionRecordsDbPath);
  86. //}
  87. //产品加载记录
  88. if (!IsHaveTable("LoadProductRecords", FilePath.ProductionRecordsDbPath))
  89. {
  90. CreateTable("LoadProductRecords", "(Time DATETIME,ProductID TEXT,ProductName TEXT,IsAutoLoad BOOL)", FilePath.ProductionRecordsDbPath);
  91. }
  92. //锁付结果记录
  93. EnsureLockResultTable(FilePath.ProductionRecordsDbPath);
  94. return true;
  95. }
  96. catch (Exception ex)
  97. {
  98. LogHelper.WriteLogError("数据库初始化失败!", ex);
  99. return false;
  100. }
  101. }
  102. #region 用户权限
  103. /// <summary>
  104. /// 获取所有的用户
  105. /// </summary>
  106. /// <returns></returns>
  107. public static List<User> GetAllUser()
  108. {
  109. try
  110. {
  111. //创建连接字符串
  112. SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", FilePath.UserDbPath));
  113. //打开数据库
  114. if (conn.State != ConnectionState.Open)
  115. {
  116. conn.Open();
  117. }
  118. string query = "select * from Users";
  119. //创建命令
  120. SQLiteCommand cmd = new SQLiteCommand(query, conn);
  121. //执行命令
  122. SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
  123. DataTable dt = new DataTable();
  124. da.Fill(dt);
  125. da.Dispose();
  126. List<User> users = new List<User>();
  127. users.Clear();
  128. for (int i = 0; i < dt.Rows.Count; i++)
  129. {
  130. users.Add(new User()
  131. {
  132. UserName = dt.Rows[i].ItemArray[0].ToString(),
  133. UserPassword = dt.Rows[i].ItemArray[1].ToString(),
  134. userPart = (UserPart)Enum.Parse(typeof(UserPart), dt.Rows[i].ItemArray[2].ToString()),
  135. CreateTime = Convert.ToDateTime(dt.Rows[i].ItemArray[3].ToString()),
  136. IsRemember = (bool)(dt.Rows[i].ItemArray[4]),
  137. }); ;
  138. }
  139. dt.Dispose();
  140. //释放资源
  141. conn.Close();
  142. cmd.Dispose();
  143. conn.Dispose();
  144. return users;
  145. }
  146. catch (Exception ex)
  147. {
  148. LogHelper.WriteLogError("加载用户权限信息时出错!", ex);
  149. return null;
  150. }
  151. }
  152. /// <summary>
  153. /// 记住用户
  154. /// </summary>
  155. /// <param name="UserName"></param>
  156. public static void RememberUser(string UserName)
  157. {
  158. using (SQLiteConnection connection = new SQLiteConnection(string.Format("Data Source={0};Version=3;", FilePath.UserDbPath)))
  159. {
  160. connection.Open();
  161. using (SQLiteCommand command = new SQLiteCommand("UPDATE Users SET IsRemember = False", connection))
  162. {
  163. command.ExecuteNonQuery();
  164. command.CommandText= $"UPDATE Users SET IsRemember = True WHERE UserName = '{UserName}'";
  165. command.ExecuteNonQuery();
  166. }
  167. }
  168. }
  169. /// <summary>
  170. /// 清除记住用户
  171. /// </summary>
  172. public static void NotRememberUser()
  173. {
  174. using (SQLiteConnection connection = new SQLiteConnection(string.Format("Data Source={0};Version=3;", FilePath.UserDbPath)))
  175. {
  176. connection.Open();
  177. using (SQLiteCommand command = new SQLiteCommand("UPDATE Users SET IsRemember = False", connection))
  178. {
  179. command.ExecuteNonQuery();
  180. }
  181. }
  182. }
  183. /// <summary>
  184. /// 注册用户
  185. /// </summary>
  186. /// <param name="user"></param>
  187. /// <returns></returns>
  188. public static Tuple<bool,string> SignUp(User user)
  189. {
  190. using (SQLiteConnection connection = new SQLiteConnection(string.Format("Data Source={0};Version=3;", FilePath.UserDbPath)))
  191. {
  192. using (SQLiteCommand command = new SQLiteCommand($"select * from Users WHERE UserName='{user.UserName}'", connection))
  193. {
  194. connection.Open();
  195. // 执行命令
  196. if (command.ExecuteScalar() != null)
  197. {
  198. return new Tuple<bool, string>(false,"已存在同名用户");
  199. }
  200. command.CommandText = $"insert into Users(UserName, UserPassword, UserPart, AddTime,IsRemember) values('{user.UserName}', '{user.UserPassword}', '{user.userPart.ToString()}', '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}',False)";
  201. command.ExecuteNonQuery();
  202. return new Tuple<bool, string>(true, "");
  203. }
  204. }
  205. }
  206. #endregion
  207. #region 产品加载记录
  208. /// <summary>
  209. /// 添加一条产品加载记录至数据库
  210. /// </summary>
  211. /// <param name="id"></param>
  212. /// <param name="productName"></param>
  213. /// <param name="IsAuto"></param>
  214. public static void AddLoadProductRecord(Guid id, string productName, bool IsAuto)
  215. {
  216. try
  217. {
  218. string cmd = $"insert into LoadProductRecords(Time,ProductID,ProductName,IsAutoLoad) values('{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}','{id.ToString()}','{productName}',{IsAuto})";
  219. WriteCommandToDatabase(cmd, FilePath.ProductionRecordsDbPath);
  220. }
  221. catch (Exception ex)
  222. {
  223. LogHelper.WriteLogError("添加一条产品加载记录至数据库时出错!", ex);
  224. }
  225. }
  226. /// <summary>
  227. /// 获取最后一次加载的产品
  228. /// </summary>
  229. /// <returns></returns>
  230. public static Guid GetLastLoadProduct()
  231. {
  232. try
  233. {
  234. using (SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", FilePath.ProductionRecordsDbPath)))
  235. {
  236. if (conn.State != ConnectionState.Open)
  237. {
  238. conn.Open();
  239. }
  240. string query = "select ProductID from LoadProductRecords order by Time desc limit 1";
  241. // 创建命令对象
  242. using (SQLiteCommand command = new SQLiteCommand(query, conn))
  243. {
  244. // 执行查询,获取结果
  245. object result = command.ExecuteScalar();
  246. // 检查结果是否为 null
  247. if (result != null)
  248. {
  249. return Guid.Parse(result.ToString());
  250. }
  251. else
  252. {
  253. return Guid.Empty;
  254. }
  255. }
  256. }
  257. }
  258. catch (Exception ex)
  259. {
  260. LogHelper.WriteLogError("获取最后一次加载的产品时出错!", ex);
  261. return Guid.Empty;
  262. }
  263. }
  264. /// <summary>
  265. /// 修改产品名称
  266. /// </summary>
  267. /// <param name="NewProduct"></param>
  268. /// <param name="OldProductName"></param>
  269. public static void RevampProductName(ProductModel NewProduct, string OldProductName)
  270. {
  271. string dbpath = FilePath.ProductsPath + "//" + NewProduct.Name + "//" + NewProduct.Name + ".db";
  272. using (SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbpath)))
  273. {
  274. if (conn.State != ConnectionState.Open)
  275. {
  276. conn.Open();
  277. }
  278. foreach (var item in NewProduct.CameraProcedures)
  279. {
  280. foreach (var item1 in item.ProcedureModels)
  281. {
  282. string procname = item1.Name.Split('-')[2];
  283. string strold= $"{OldProductName}_{item1.CameraName}_{procname}";
  284. string strnew = $"{NewProduct.Name}_{item1.CameraName}_{procname}";
  285. string query = $"ALTER TABLE {strold} RENAME TO {strnew}";
  286. // 创建命令对象
  287. using (SQLiteCommand command = new SQLiteCommand(query, conn))
  288. {
  289. /// 执行命令
  290. command.ExecuteNonQuery();
  291. }
  292. }
  293. }
  294. }
  295. }
  296. #endregion
  297. #region 产品生产数据记录
  298. /// <summary>
  299. /// 更新产品数据库表格配置
  300. /// </summary>
  301. /// <param name="product"></param>
  302. public static void UpdateProductDatabase(ProductModel product)
  303. {
  304. string productname = product.Name;
  305. if (char.IsDigit(productname[0]))
  306. {
  307. productname = "a" + productname;
  308. }
  309. string dbpath = FilePath.ProductsPath + "//" + product.Name + "//" + productname + ".db";
  310. if (!File.Exists(dbpath))
  311. {
  312. //如果数据库文件不存在,则创建一个数据库
  313. SQLiteConnection.CreateFile(dbpath);
  314. }
  315. foreach (var item in product.CameraProcedures)
  316. {
  317. //遍历所有的流程
  318. foreach (var item1 in item.ProcedureModels)
  319. {
  320. if (item1.ToolBlock==null)
  321. {
  322. continue;
  323. }
  324. CogToolBlockTerminalCollection outputCollection = item1.ToolBlock.Outputs;
  325. string tablename = item1.Name.Replace('-','_').Replace(' ', '_').Trim();
  326. if (char.IsDigit(tablename[0]))
  327. {
  328. tablename = "a" + tablename;
  329. }
  330. //如果不存在表,则创建一个表
  331. if (!IsHaveTable(tablename, dbpath))
  332. {
  333. StringBuilder sb = new StringBuilder();
  334. foreach (CogToolBlockTerminal output in outputCollection)
  335. {
  336. sb.Append($"_{output.Name.Replace(' ', '_').Trim()} TEXT,");
  337. }
  338. CreateTable(tablename, $"(_Time DATETIME,{sb.ToString().TrimEnd(',')})", dbpath);
  339. }
  340. else
  341. {
  342. if (!IsHaveColumn("_Time", tablename, dbpath))
  343. {
  344. AddColumn("_Time", "DATETIME", tablename, dbpath);
  345. }
  346. foreach (CogToolBlockTerminal output in outputCollection)
  347. {
  348. if (!IsHaveColumn("_" + output.Name.Replace(' ', '_').Trim(), tablename, dbpath))
  349. {
  350. AddColumn("_" + output.Name.Replace(' ', '_').Trim(), "TEXT", tablename, dbpath);
  351. }
  352. }
  353. }
  354. }
  355. }
  356. //如果不存在表,则创建一个表
  357. if (!IsHaveTable("ProductionRecords", dbpath))
  358. {
  359. CreateTable("ProductionRecords", $"(_Time DATETIME,_Content TEXT)", dbpath);
  360. }
  361. EnsureLockResultTable(dbpath);
  362. }
  363. /// <summary>
  364. /// 增加一条相机拍照记录
  365. /// </summary>
  366. /// <param name="ProductName"></param>
  367. /// <param name="ProcedureName"></param>
  368. /// <param name="result"></param>
  369. public static void AddCameraRecords(string ProductName, string ProcedureName, CogToolBlockTerminalCollection result)
  370. {
  371. try
  372. {
  373. string productname = ProductName;
  374. if (char.IsDigit(productname[0]))
  375. {
  376. productname = "a" + productname;
  377. }
  378. string dbpath = FilePath.ProductsPath + "//" + ProductName + "//" + productname + ".db";
  379. if (!File.Exists(dbpath))
  380. {
  381. //如果数据库文件不存在,则创建一个数据库
  382. SQLiteConnection.CreateFile(dbpath);
  383. }
  384. string tablename = ProcedureName.Replace('-', '_').Replace(' ', '_').Trim();
  385. if (char.IsDigit(tablename[0]))
  386. {
  387. tablename = "a" + tablename;
  388. }
  389. if (!IsHaveTable(tablename, dbpath))
  390. {
  391. StringBuilder sb = new StringBuilder();
  392. foreach (CogToolBlockTerminal output in result)
  393. {
  394. sb.Append($"_{output.Name.Replace(' ', '_').Trim()} TEXT,");
  395. }
  396. CreateTable(tablename, $"(_Time DATETIME,{sb.ToString().TrimEnd(',')})", dbpath);
  397. }
  398. StringBuilder ha = new StringBuilder();
  399. StringBuilder vs = new StringBuilder();
  400. foreach (CogToolBlockTerminal output in result)
  401. {
  402. ha.Append($"_{output.Name.Replace(' ', '_').Trim()},");
  403. if (output.Value!=null)
  404. {
  405. vs.Append($"'{output.Value.ToString()}',");
  406. }
  407. else
  408. {
  409. vs.Append($"'null',");
  410. }
  411. }
  412. string cmd = $"insert into {tablename}(_Time,{ha.ToString().TrimEnd(',')}) values('{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}',{vs.ToString().TrimEnd(',')})";
  413. WriteCommandToDatabase(cmd, dbpath);
  414. }
  415. catch (Exception ex)
  416. {
  417. LogHelper.WriteLogError("增加一条相机拍照记录至数据库时出错!", ex);
  418. }
  419. }
  420. /// <summary>
  421. /// 增加一条产品的生产记录至数据库
  422. /// </summary>
  423. /// <param name="ProductName"></param>
  424. /// <param name="_Content"></param>
  425. /// <param name="_value"></param>
  426. public static void AddProductProductionRecords(string ProductName,string _Content)
  427. {
  428. try
  429. {
  430. string productname = ProductName;
  431. if (char.IsDigit(productname[0]))
  432. {
  433. productname = "a" + productname;
  434. }
  435. string dbpath = FilePath.ProductsPath + "//" + ProductName + "//" + productname + ".db";
  436. string tablename = "ProductionRecords";
  437. string cmd = $"insert into {tablename}(_Time,_Content) values('{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}','{_Content}')";
  438. WriteCommandToDatabase(cmd, dbpath);
  439. }
  440. catch (Exception ex)
  441. {
  442. LogHelper.WriteLogError("增加一条产品的生产记录至数据库时出错!", ex);
  443. }
  444. }
  445. private const string LockResultTableName = "LockResults";
  446. private const string LockResultTableColumns =
  447. "(Time DATETIME, Number INTEGER, LockTurns REAL, LockTorque REAL, LockDuration REAL, LockPassed BOOL, ScrewdriverProgramNumber INTEGER, CurveCsvPath TEXT, CurveImagePath TEXT)";
  448. /// <summary>
  449. /// 确保锁付结果表存在
  450. /// </summary>
  451. public static void EnsureLockResultTable(string dbpath)
  452. {
  453. if (!File.Exists(dbpath))
  454. {
  455. string dir = System.IO.Path.GetDirectoryName(dbpath);
  456. if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
  457. {
  458. Directory.CreateDirectory(dir);
  459. }
  460. SQLiteConnection.CreateFile(dbpath);
  461. }
  462. if (!IsHaveTable(LockResultTableName, dbpath))
  463. {
  464. CreateTable(LockResultTableName, LockResultTableColumns, dbpath);
  465. }
  466. }
  467. private static string GetProductDatabasePath(string productName)
  468. {
  469. string productname = productName;
  470. if (char.IsDigit(productname[0]))
  471. {
  472. productname = "a" + productname;
  473. }
  474. return FilePath.ProductsPath + "//" + productName + "//" + productname + ".db";
  475. }
  476. private static string EscapeSqlString(string value)
  477. {
  478. return (value ?? string.Empty).Replace("'", "''");
  479. }
  480. /// <summary>
  481. /// 增加一条锁付结果记录至数据库(全局库;若已加载产品则同步写入产品库)
  482. /// </summary>
  483. public static void AddLockResultRecord(LockResult result, string curveCsvPath, string curveImagePath, string productName = null)
  484. {
  485. try
  486. {
  487. EnsureLockResultTable(FilePath.ProductionRecordsDbPath);
  488. InsertLockResultRecord(result, curveCsvPath, curveImagePath, FilePath.ProductionRecordsDbPath);
  489. if (!string.IsNullOrWhiteSpace(productName))
  490. {
  491. string dbpath = GetProductDatabasePath(productName);
  492. EnsureLockResultTable(dbpath);
  493. InsertLockResultRecord(result, curveCsvPath, curveImagePath, dbpath);
  494. }
  495. }
  496. catch (Exception ex)
  497. {
  498. LogHelper.WriteLogError("增加锁付结果记录至数据库时出错!", ex);
  499. }
  500. }
  501. private static void InsertLockResultRecord(LockResult result, string curveCsvPath, string curveImagePath, string dbpath)
  502. {
  503. string time = result.Timestamp.ToString("yyyy-MM-dd HH:mm:ss");
  504. string passed = result.LockPassed ? "True" : "False";
  505. var inv = System.Globalization.CultureInfo.InvariantCulture;
  506. string cmd = $"insert into {LockResultTableName}(Time,Number,LockTurns,LockTorque,LockDuration,LockPassed,ScrewdriverProgramNumber,CurveCsvPath,CurveImagePath) " +
  507. $"values('{time}',{result.Number},{result.LockTurns.ToString(inv)},{result.LockTorque.ToString(inv)},{result.LockDuration.ToString(inv)},{passed},{result.ScrewdriverProgramNumber}," +
  508. $"'{EscapeSqlString(curveCsvPath)}','{EscapeSqlString(curveImagePath)}')";
  509. WriteCommandToDatabase(cmd, dbpath);
  510. }
  511. /// <summary>
  512. /// 获取生产总数
  513. /// </summary>
  514. /// <param name="ProductName"></param>
  515. /// <returns></returns>
  516. public static Int64 GetTotalQuantity(string ProductName)
  517. {
  518. try
  519. {
  520. string productname = ProductName;
  521. if (char.IsDigit(productname[0]))
  522. {
  523. productname = "a" + productname;
  524. }
  525. string dbpath = FilePath.ProductsPath + "//" + ProductName + "//" + productname + ".db";
  526. using (SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbpath)))
  527. {
  528. if (conn.State != ConnectionState.Open)
  529. {
  530. conn.Open();
  531. }
  532. string query = "SELECT COUNT(*) FROM ProductionRecords";
  533. // 创建命令对象
  534. using (SQLiteCommand command = new SQLiteCommand(query, conn))
  535. {
  536. // 执行查询,获取结果
  537. object result = command.ExecuteScalar();
  538. // 检查结果是否为 null
  539. if (result != null)
  540. {
  541. return Int64.Parse(result.ToString());
  542. }
  543. else
  544. {
  545. return 0;
  546. }
  547. }
  548. }
  549. }
  550. catch (Exception ex)
  551. {
  552. LogHelper.WriteLogError("从数据库获取生产总数时出错!", ex);
  553. return 0;
  554. }
  555. }
  556. /// <summary>
  557. /// 获取当月的生产总数
  558. /// </summary>
  559. /// <param name="ProductName"></param>
  560. /// <returns></returns>
  561. public static Int64 GetTotalQuantityMonth(string ProductName)
  562. {
  563. try
  564. {
  565. string productname = ProductName;
  566. if (char.IsDigit(productname[0]))
  567. {
  568. productname = "a" + productname;
  569. }
  570. string dbpath = FilePath.ProductsPath + "//" + ProductName + "//" + productname + ".db";
  571. using (SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbpath)))
  572. {
  573. if (conn.State != ConnectionState.Open)
  574. {
  575. conn.Open();
  576. }
  577. DateTime start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0);
  578. DateTime end = start.AddMonths(1);
  579. string query = $"SELECT COUNT(*) FROM ProductionRecords WHERE _Time>='{start.ToString("yyyy-MM-dd HH:mm:ss")}' AND _Time<='{end.ToString("yyyy-MM-dd HH:mm:ss")}'";
  580. // 创建命令对象
  581. using (SQLiteCommand command = new SQLiteCommand(query, conn))
  582. {
  583. // 执行查询,获取结果
  584. object result = command.ExecuteScalar();
  585. // 检查结果是否为 null
  586. if (result != null)
  587. {
  588. return Int64.Parse(result.ToString());
  589. }
  590. else
  591. {
  592. return 0;
  593. }
  594. }
  595. }
  596. }
  597. catch (Exception ex)
  598. {
  599. LogHelper.WriteLogError("获取获取当月的生产总数时出错!", ex);
  600. return 0;
  601. }
  602. }
  603. /// <summary>
  604. /// 获取当前周的生产总数
  605. /// </summary>
  606. /// <param name="ProductName"></param>
  607. /// <returns></returns>
  608. public static Int64 GetTotalQuantityWeek(string ProductName)
  609. {
  610. try
  611. {
  612. string productname = ProductName;
  613. if (char.IsDigit(productname[0]))
  614. {
  615. productname = "a" + productname;
  616. }
  617. string dbpath = FilePath.ProductsPath + "//" + ProductName + "//" + productname + ".db";
  618. using (SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbpath)))
  619. {
  620. if (conn.State != ConnectionState.Open)
  621. {
  622. conn.Open();
  623. }
  624. DateTime start = DateTime.Now.AddDays(-((int)DateTime.Now.DayOfWeek-1));
  625. DateTime end = start.AddDays(7);
  626. start = new DateTime(start.Year, start.Month, start.Day, 0, 0, 0);
  627. end= new DateTime(end.Year, end.Month, end.Day, 0, 0, 0);
  628. string query = $"SELECT COUNT(*) FROM ProductionRecords WHERE _Time>='{start.ToString("yyyy-MM-dd HH:mm:ss")}' AND _Time<='{end.ToString("yyyy-MM-dd HH:mm:ss")}'";
  629. // 创建命令对象
  630. using (SQLiteCommand command = new SQLiteCommand(query, conn))
  631. {
  632. // 执行查询,获取结果
  633. object result = command.ExecuteScalar();
  634. // 检查结果是否为 null
  635. if (result != null)
  636. {
  637. return Int64.Parse(result.ToString());
  638. }
  639. else
  640. {
  641. return 0;
  642. }
  643. }
  644. }
  645. }
  646. catch (Exception ex)
  647. {
  648. LogHelper.WriteLogError("获取当前周的生产总数时出错!", ex);
  649. return 0;
  650. }
  651. }
  652. /// <summary>
  653. /// 获取当天的生产总数
  654. /// </summary>
  655. /// <param name="ProductName"></param>
  656. /// <returns></returns>
  657. public static Int64 GetTotalQuantityToday(string ProductName)
  658. {
  659. try
  660. {
  661. string productname = ProductName;
  662. if (char.IsDigit(productname[0]))
  663. {
  664. productname = "a" + productname;
  665. }
  666. string dbpath = FilePath.ProductsPath + "//" + ProductName + "//" + productname + ".db";
  667. using (SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbpath)))
  668. {
  669. if (conn.State != ConnectionState.Open)
  670. {
  671. conn.Open();
  672. }
  673. DateTime now= DateTime.Now;
  674. DateTime start = new DateTime(now.Year, now.Month, now.Day,0,0,0);
  675. string query = $"SELECT COUNT(*) FROM ProductionRecords WHERE _Time>='{start.ToString("yyyy-MM-dd HH:mm:ss")}' AND _Time<='{now.ToString("yyyy-MM-dd HH:mm:ss")}'";
  676. // 创建命令对象
  677. using (SQLiteCommand command = new SQLiteCommand(query, conn))
  678. {
  679. // 执行查询,获取结果
  680. object result = command.ExecuteScalar();
  681. // 检查结果是否为 null
  682. if (result != null)
  683. {
  684. return Int64.Parse(result.ToString());
  685. }
  686. else
  687. {
  688. return 0;
  689. }
  690. }
  691. }
  692. }
  693. catch (Exception ex)
  694. {
  695. LogHelper.WriteLogError("获取当天的生产总数时出错!", ex);
  696. return 0;
  697. }
  698. }
  699. /// <summary>
  700. /// 获取UPH
  701. /// </summary>
  702. /// <param name="ProductName"></param>
  703. /// <returns></returns>
  704. public static Int64 GetUPH(string ProductName)
  705. {
  706. try
  707. {
  708. string productname = ProductName;
  709. if (char.IsDigit(productname[0]))
  710. {
  711. productname = "a" + productname;
  712. }
  713. string dbpath = FilePath.ProductsPath + "//" + ProductName + "//" + productname + ".db";
  714. using (SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbpath)))
  715. {
  716. if (conn.State != ConnectionState.Open)
  717. {
  718. conn.Open();
  719. }
  720. DateTime now = DateTime.Now;
  721. DateTime start = now.AddHours(-1);
  722. string query = $"SELECT COUNT(*) FROM ProductionRecords WHERE _Time>='{start.ToString("yyyy-MM-dd HH:mm:ss")}' AND _Time<='{now.ToString("yyyy-MM-dd HH:mm:ss")}'";
  723. // 创建命令对象
  724. using (SQLiteCommand command = new SQLiteCommand(query, conn))
  725. {
  726. // 执行查询,获取结果
  727. object result = command.ExecuteScalar();
  728. // 检查结果是否为 null
  729. if (result != null)
  730. {
  731. return Int64.Parse(result.ToString());
  732. }
  733. else
  734. {
  735. return 0;
  736. }
  737. }
  738. }
  739. }
  740. catch (Exception ex)
  741. {
  742. LogHelper.WriteLogError("获取UPH时出错!", ex);
  743. return 0;
  744. }
  745. }
  746. /// <summary>
  747. /// 产品计数清零
  748. /// </summary>
  749. /// <param name="ProductName"></param>
  750. public static void ResetCounter(string ProductName)
  751. {
  752. try
  753. {
  754. string productname = ProductName;
  755. if (char.IsDigit(productname[0]))
  756. {
  757. productname = "a" + productname;
  758. }
  759. string dbpath = FilePath.ProductsPath + "//" + ProductName + "//" + productname + ".db";
  760. using (SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbpath)))
  761. {
  762. if (conn.State != ConnectionState.Open)
  763. {
  764. conn.Open();
  765. }
  766. int index = 1;
  767. string newTableName = $"ProductionRecords1";
  768. while (true)
  769. {
  770. newTableName =$"ProductionRecords{index}";
  771. string query1 = $"select COUNT(*) from sqlite_master where type='table' and name ='{newTableName}'";
  772. // 创建命令对象
  773. using (SQLiteCommand command = new SQLiteCommand(query1, conn))
  774. {
  775. // 执行查询,获取结果
  776. object result = command.ExecuteScalar();
  777. if (!(result != null && Convert.ToBoolean(result)))
  778. {
  779. break;
  780. }
  781. }
  782. index++;
  783. }
  784. //复制数据表
  785. string query = $"CREATE TABLE {newTableName} AS SELECT * FROM ProductionRecords";
  786. using (SQLiteCommand command = new SQLiteCommand(query, conn))
  787. {
  788. command.ExecuteNonQuery();
  789. }
  790. //清空数据表
  791. query = $"DELETE FROM ProductionRecords";
  792. using (SQLiteCommand command = new SQLiteCommand(query, conn))
  793. {
  794. command.ExecuteNonQuery();
  795. }
  796. }
  797. }
  798. catch (Exception ex)
  799. {
  800. LogHelper.WriteLogError("产品计数清零时出错!", ex);
  801. }
  802. }
  803. #endregion
  804. #region 报警记录
  805. /// <summary>
  806. /// 添加一条报警记录
  807. /// </summary>
  808. /// <param name="alarmmesg"></param>
  809. public static void AppendAlarm(string alarmmesg)
  810. {
  811. try
  812. {
  813. string cmd = $"insert into Alarm(Time,ErrorCode,ErrorMessage,Countermeasure) values('{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}','0','alarmmesg','')";
  814. WriteCommandToDatabase(cmd, FilePath.ProductionRecordsDbPath);
  815. }
  816. catch (Exception ex)
  817. {
  818. LogHelper.WriteLogError("添加一条报警记录至数据库时出错!", ex);
  819. }
  820. }
  821. #endregion
  822. #region 数据统计查询
  823. /// <summary>
  824. /// 获取产品的总的统计数据
  825. /// </summary>
  826. /// <param name="ProductName"></param>
  827. /// <returns></returns>
  828. public static Dictionary<string,Int64> GetTotalProductStatistical(string ProductName)
  829. {
  830. Dictionary<string, Int64> list = new Dictionary<string, Int64>();
  831. var items = GetAllItemForProductionRecords(ProductName);
  832. for (int i = 0; i < items.Length; i++)
  833. {
  834. var count = GetItemCountForProductionRecords(ProductName, items[i]);
  835. list.Add(items[i], count);
  836. }
  837. return list;
  838. }
  839. /// <summary>
  840. /// 获取当前月每天的产能统计
  841. /// </summary>
  842. /// <param name="ProductName"></param>
  843. /// <returns></returns>
  844. public static Dictionary<DateTime, Dictionary<string, Int64>> GetProductStatisticalMonth(string ProductName)
  845. {
  846. Dictionary<DateTime, Dictionary<string, Int64>> list = new Dictionary<DateTime, Dictionary<string, long>>();
  847. try
  848. {
  849. var Items = GetAllItemForProductionRecords(ProductName);
  850. string dbpath = FilePath.ProductsPath + "//" + ProductName + "//" + ProductName + ".db";
  851. using (SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbpath)))
  852. {
  853. if (conn.State != ConnectionState.Open)
  854. {
  855. conn.Open();
  856. }
  857. DateTime start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0);
  858. DateTime end = start.AddMonths(1);
  859. int index = 1;
  860. while (true)
  861. {
  862. DateTime curent= start.AddDays(index);
  863. list.Add(curent.AddDays(-1),new Dictionary<string, long>());
  864. foreach (var item in Items)
  865. {
  866. string query = $"SELECT COUNT(*) FROM ProductionRecords WHERE _Time>='{curent.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss")}' AND _Time<='{curent.ToString("yyyy-MM-dd HH:mm:ss")}' AND _Content='{item}'";
  867. // 创建命令对象
  868. using (SQLiteCommand command = new SQLiteCommand(query, conn))
  869. {
  870. // 执行查询,获取结果
  871. object result = command.ExecuteScalar();
  872. // 检查结果是否为 null
  873. if (result != null)
  874. {
  875. list[curent.AddDays(-1)].Add(item, Int64.Parse(result.ToString()));
  876. }
  877. else
  878. {
  879. list[curent.AddDays(-1)].Add(item, 0);
  880. }
  881. }
  882. }
  883. if (curent >= end)
  884. break;
  885. index++;
  886. }
  887. }
  888. return list;
  889. }
  890. catch (Exception ex)
  891. {
  892. LogHelper.WriteLogError("获取当前月每天的产能统计时出错!", ex);
  893. return list;
  894. }
  895. }
  896. /// <summary>
  897. /// 获取当前周每天的产能统计
  898. /// </summary>
  899. /// <param name="ProductName"></param>
  900. /// <returns></returns>
  901. public static Dictionary<int, Dictionary<string, Int64>> GetProductStatisticalWeek(string ProductName)
  902. {
  903. Dictionary<int, Dictionary<string, Int64>> list = new Dictionary<int, Dictionary<string, long>>();
  904. try
  905. {
  906. var Items = GetAllItemForProductionRecords(ProductName);
  907. string dbpath = FilePath.ProductsPath + "//" + ProductName + "//" + ProductName + ".db";
  908. using (SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbpath)))
  909. {
  910. if (conn.State != ConnectionState.Open)
  911. {
  912. conn.Open();
  913. }
  914. DateTime start = DateTime.Now.AddDays(-((int)DateTime.Now.DayOfWeek - 1));
  915. DateTime end = start.AddDays(7);
  916. int index = 1;
  917. while (true)
  918. {
  919. DateTime curent = start.AddDays(index);
  920. list.Add(index, new Dictionary<string, long>());
  921. foreach (var item in Items)
  922. {
  923. string query = $"SELECT COUNT(*) FROM ProductionRecords WHERE _Time>='{curent.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss")}' AND _Time<='{curent.ToString("yyyy-MM-dd HH:mm:ss")}' AND _Content='{item}'";
  924. // 创建命令对象
  925. using (SQLiteCommand command = new SQLiteCommand(query, conn))
  926. {
  927. // 执行查询,获取结果
  928. object result = command.ExecuteScalar();
  929. // 检查结果是否为 null
  930. if (result != null)
  931. {
  932. list[index].Add(item, Int64.Parse(result.ToString()));
  933. }
  934. else
  935. {
  936. list[index].Add(item, 0);
  937. }
  938. }
  939. }
  940. if (curent >= end)
  941. break;
  942. index++;
  943. }
  944. }
  945. return list;
  946. }
  947. catch (Exception ex)
  948. {
  949. LogHelper.WriteLogError("获取当前周每天的产能统计时出错!", ex);
  950. return list;
  951. }
  952. }
  953. /// <summary>
  954. /// 获取今天每小时的产能统计
  955. /// </summary>
  956. /// <param name="ProductName"></param>
  957. /// <returns></returns>
  958. public static Dictionary<int, Dictionary<string, Int64>> GetProductStatisticalDay(string ProductName)
  959. {
  960. Dictionary<int, Dictionary<string, Int64>> list = new Dictionary<int, Dictionary<string, long>>();
  961. try
  962. {
  963. var Items = GetAllItemForProductionRecords(ProductName);
  964. string dbpath = FilePath.ProductsPath + "//" + ProductName + "//" + ProductName + ".db";
  965. using (SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbpath)))
  966. {
  967. if (conn.State != ConnectionState.Open)
  968. {
  969. conn.Open();
  970. }
  971. DateTime start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
  972. DateTime end = start.AddDays(1);
  973. int index = 1;
  974. while (true)
  975. {
  976. DateTime curent = start.AddHours(index);
  977. list.Add(index, new Dictionary<string, long>());
  978. foreach (var item in Items)
  979. {
  980. string query = $"SELECT COUNT(*) FROM ProductionRecords WHERE _Time>='{curent.AddHours(-1).ToString("yyyy-MM-dd HH:mm:ss")}' AND _Time<='{curent.ToString("yyyy-MM-dd HH:mm:ss")}' AND _Content='{item}'";
  981. // 创建命令对象
  982. using (SQLiteCommand command = new SQLiteCommand(query, conn))
  983. {
  984. // 执行查询,获取结果
  985. object result = command.ExecuteScalar();
  986. // 检查结果是否为 null
  987. if (result != null)
  988. {
  989. list[index].Add(item, Int64.Parse(result.ToString()));
  990. }
  991. else
  992. {
  993. list[index].Add(item, 0);
  994. }
  995. }
  996. }
  997. if (curent >= end)
  998. break;
  999. index++;
  1000. }
  1001. }
  1002. return list;
  1003. }
  1004. catch (Exception ex)
  1005. {
  1006. LogHelper.WriteLogError("获取今天每小时的产能统计时出错!", ex);
  1007. return list;
  1008. }
  1009. }
  1010. /// <summary>
  1011. /// 从数据库获取生产计数的类别项
  1012. /// </summary>
  1013. /// <param name="ProductName"></param>
  1014. /// <returns></returns>
  1015. public static string[] GetAllItemForProductionRecords(string ProductName)
  1016. {
  1017. try
  1018. {
  1019. List<string> items=new List<string>();
  1020. string dbpath = FilePath.ProductsPath + "//" + ProductName + "//" + ProductName + ".db";
  1021. using (SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbpath)))
  1022. {
  1023. if (conn.State != ConnectionState.Open)
  1024. {
  1025. conn.Open();
  1026. }
  1027. string query = $"SELECT DISTINCT _Content FROM ProductionRecords";
  1028. // 创建命令对象
  1029. using (SQLiteCommand command = new SQLiteCommand(query, conn))
  1030. {
  1031. using (SQLiteDataReader reader = command.ExecuteReader())
  1032. {
  1033. while (reader.Read())
  1034. {
  1035. string item = reader["_Content"].ToString();
  1036. items.Add(item);
  1037. }
  1038. }
  1039. return items.ToArray();
  1040. }
  1041. }
  1042. }
  1043. catch (Exception ex)
  1044. {
  1045. LogHelper.WriteLogError("从数据库获取生产计数的类别项时出错!", ex);
  1046. return null;
  1047. }
  1048. }
  1049. /// <summary>
  1050. /// 从数据库中获取指定项的统计数量
  1051. /// </summary>
  1052. /// <param name="ProductName"></param>
  1053. /// <param name="item"></param>
  1054. /// <returns></returns>
  1055. public static Int64 GetItemCountForProductionRecords(string ProductName,string item)
  1056. {
  1057. try
  1058. {
  1059. List<string> items = new List<string>();
  1060. string dbpath = FilePath.ProductsPath + "//" + ProductName + "//" + ProductName + ".db";
  1061. using (SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbpath)))
  1062. {
  1063. if (conn.State != ConnectionState.Open)
  1064. {
  1065. conn.Open();
  1066. }
  1067. string query = $"SELECT COUNT(*) FROM ProductionRecords WHERE _Content='{item}'";
  1068. // 创建命令对象
  1069. using (SQLiteCommand command = new SQLiteCommand(query, conn))
  1070. {
  1071. // 执行查询,获取结果
  1072. object result = command.ExecuteScalar();
  1073. // 检查结果是否为 null
  1074. if (result != null)
  1075. {
  1076. return Int64.Parse(result.ToString());
  1077. }
  1078. else
  1079. {
  1080. return 0;
  1081. }
  1082. }
  1083. }
  1084. }
  1085. catch (Exception ex)
  1086. {
  1087. LogHelper.WriteLogError("从数据库中获取指定项的统计数量时出错!", ex);
  1088. return 0;
  1089. }
  1090. }
  1091. /// <summary>
  1092. /// 从数据库中获取指定项的统计数量
  1093. /// </summary>
  1094. /// <param name="ProductName"></param>
  1095. /// <param name="item"></param>
  1096. /// <param name="start"></param>
  1097. /// <param name="end"></param>
  1098. /// <returns></returns>
  1099. public static Int64 GetItemCountForProductionRecords(string ProductName, string item,DateTime start,DateTime end)
  1100. {
  1101. try
  1102. {
  1103. List<string> items = new List<string>();
  1104. string dbpath = FilePath.ProductsPath + "//" + ProductName + "//" + ProductName + ".db";
  1105. using (SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbpath)))
  1106. {
  1107. if (conn.State != ConnectionState.Open)
  1108. {
  1109. conn.Open();
  1110. }
  1111. string query = $"SELECT COUNT(*) FROM ProductionRecords WHERE _Content='{item}' AND _Time>='{start.ToString("yyyy-MM-dd HH:mm:ss")}' AND _Time<='{end.ToString("yyyy-MM-dd HH:mm:ss")}'";
  1112. // 创建命令对象
  1113. using (SQLiteCommand command = new SQLiteCommand(query, conn))
  1114. {
  1115. // 执行查询,获取结果
  1116. object result = command.ExecuteScalar();
  1117. // 检查结果是否为 null
  1118. if (result != null)
  1119. {
  1120. return Int64.Parse(result.ToString());
  1121. }
  1122. else
  1123. {
  1124. return 0;
  1125. }
  1126. }
  1127. }
  1128. }
  1129. catch (Exception ex)
  1130. {
  1131. LogHelper.WriteLogError("从数据库中获取指定项的统计数量时出错!", ex);
  1132. return 0;
  1133. }
  1134. }
  1135. /// <summary>
  1136. /// 获取产品流程相机数据记录
  1137. /// </summary>
  1138. /// <param name="ProductName"></param>
  1139. /// <param name="ProcedureName"></param>
  1140. /// <returns></returns>
  1141. public static Task<DataTable> GetProductProcessRecords(string ProductName, string ProcedureName, DateTime? dt1 = null, DateTime? dt2 = null)
  1142. {
  1143. try
  1144. {
  1145. string dbpath = FilePath.ProductsPath + "//" + ProductName + "//" + ProductName + ".db";
  1146. using (SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbpath)))
  1147. {
  1148. if (conn.State != ConnectionState.Open)
  1149. {
  1150. conn.Open();
  1151. }
  1152. string query = $"select * from {ProcedureName.Replace('-','_').Replace(' ', '_').Trim()}";
  1153. if (dt1!=null && dt2!=null)
  1154. {
  1155. query = $"select * from {ProcedureName.Replace('-', '_').Replace(' ', '_').Trim()} WHERE Time>='{((DateTime)dt1).ToString("yyyy-MM-dd HH:mm:ss")}' AND Time<='{((DateTime)dt2).ToString("yyyy-MM-dd HH:mm:ss")}'";
  1156. }
  1157. // 创建命令对象
  1158. using (SQLiteCommand command = new SQLiteCommand(query, conn))
  1159. {
  1160. using (SQLiteDataAdapter reader = new SQLiteDataAdapter(command))
  1161. {
  1162. DataTable table = new DataTable();
  1163. reader.Fill(table);
  1164. return Task.FromResult(table);
  1165. }
  1166. }
  1167. }
  1168. }
  1169. catch (Exception ex)
  1170. {
  1171. LogHelper.WriteLogError("获取产品流程相机数据记录时出错!", ex);
  1172. return Task.FromResult(new DataTable());
  1173. }
  1174. }
  1175. /// <summary>
  1176. /// 获取报警记录
  1177. /// </summary>
  1178. /// <returns></returns>
  1179. public static Task<DataTable> GetAlarmRecords(DateTime dt1, DateTime dt2)
  1180. {
  1181. try
  1182. {
  1183. using (SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", FilePath.ProductionRecordsDbPath)))
  1184. {
  1185. if (conn.State != ConnectionState.Open)
  1186. {
  1187. conn.Open();
  1188. }
  1189. string query = $"select * from Alarm WHERE Time>='{dt1.ToString("yyyy-MM-dd HH:mm:ss")}' AND Time<='{dt2.ToString("yyyy-MM-dd HH:mm:ss")}'";
  1190. // 创建命令对象
  1191. using (SQLiteCommand command = new SQLiteCommand(query, conn))
  1192. {
  1193. using (SQLiteDataAdapter reader = new SQLiteDataAdapter(command))
  1194. {
  1195. DataTable table = new DataTable();
  1196. reader.Fill(table);
  1197. return Task.FromResult(table);
  1198. }
  1199. }
  1200. }
  1201. }
  1202. catch (Exception ex)
  1203. {
  1204. LogHelper.WriteLogError("获取获取报警记录时出错!", ex);
  1205. return Task.FromResult(new DataTable());
  1206. }
  1207. }
  1208. #endregion
  1209. /// <summary>
  1210. /// 检测数据库库中是否存在表
  1211. /// </summary>
  1212. /// <param name="TableName">表名称</param>
  1213. public static bool IsHaveTable(string TableName,string dbpath)
  1214. {
  1215. try
  1216. {
  1217. //创建连接字符串
  1218. SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbpath));
  1219. //打开数据库
  1220. if (conn.State != ConnectionState.Open)
  1221. {
  1222. conn.Open();
  1223. }
  1224. string cmdStr = $"select COUNT(*) from sqlite_master where type='table' and name ='{TableName}' "; //sql语句,查询表
  1225. //创建命令
  1226. SQLiteCommand cmd = new SQLiteCommand(cmdStr, conn);
  1227. bool _Flog = false;
  1228. // 执行命令
  1229. if (Convert.ToInt32(cmd.ExecuteScalar()) == 0)
  1230. {
  1231. //该表不存在
  1232. _Flog = false;
  1233. }
  1234. else
  1235. {
  1236. //该表存在
  1237. _Flog = true;
  1238. }
  1239. //释放资源
  1240. conn.Close();
  1241. cmd.Dispose();
  1242. conn.Dispose();
  1243. return _Flog;
  1244. }
  1245. catch (Exception ex)
  1246. {
  1247. LogHelper.WriteLogError($"检测数据库库中是否存在表({TableName})时出错", ex);
  1248. return false;
  1249. }
  1250. }
  1251. /// <summary>
  1252. /// 为数据创建表
  1253. /// </summary>
  1254. /// <param name="TableName">表的名称</param>
  1255. /// <param name="column">列的名称和类型字符串(Name varchar,Team varchar, Number varchar)</param>
  1256. public static bool CreateTable(string TableName, string column,string dbpath)
  1257. {
  1258. string query = "CREATE TABLE " + TableName + " " + column;
  1259. return WriteCommandToDatabase(query, dbpath);
  1260. }
  1261. /// <summary>
  1262. /// 为表增加列
  1263. /// </summary>
  1264. /// <param name="ColumnName"></param>
  1265. /// <param name="ColumnType"></param>
  1266. /// <param name="TableName"></param>
  1267. /// <param name="dbpath"></param>
  1268. public static void AddColumn(string ColumnName,string ColumnType,string TableName, string dbpath)
  1269. {
  1270. using (SQLiteConnection connection = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbpath)))
  1271. {
  1272. // 打开数据库连接
  1273. connection.Open();
  1274. string query = $"ALTER TABLE {TableName} ADD COLUMN {ColumnName} {ColumnType}";
  1275. // 创建命令对象
  1276. using (SQLiteCommand command = new SQLiteCommand(query, connection))
  1277. {
  1278. // 执行 SQL 语句
  1279. command.ExecuteNonQuery();
  1280. }
  1281. }
  1282. }
  1283. /// <summary>
  1284. /// 将命令写入数据库
  1285. /// </summary>
  1286. /// <param name="cmdstr"></param>
  1287. public static bool WriteCommandToDatabase(string cmdstr,string dbpath)
  1288. {
  1289. try
  1290. {
  1291. //创建连接字符串
  1292. SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbpath));
  1293. //打开数据库
  1294. if (conn.State != ConnectionState.Open)
  1295. {
  1296. conn.Open();
  1297. }
  1298. //创建命令
  1299. SQLiteCommand cmd = new SQLiteCommand(cmdstr, conn);
  1300. // 执行命令
  1301. cmd.ExecuteNonQuery();
  1302. //释放资源
  1303. conn.Close();
  1304. cmd.Dispose();
  1305. conn.Dispose();
  1306. return true;
  1307. }
  1308. catch (Exception ex)
  1309. {
  1310. LogHelper.WriteLogError($"写入命令至数据库时出错:【{cmdstr}】", ex);
  1311. return false;
  1312. }
  1313. }
  1314. /// <summary>
  1315. /// 检索数据
  1316. /// </summary>
  1317. /// <param name="strCmd"></param>
  1318. /// <param name="tab"></param>
  1319. /// <returns></returns>
  1320. public static bool Select(string strCmd, ref DataTable tab,string dbPath)
  1321. {
  1322. SQLiteConnection conn;
  1323. SQLiteCommand cmd;
  1324. SQLiteDataAdapter da;
  1325. try
  1326. {
  1327. //创建连接字符串
  1328. conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbPath));
  1329. //打开数据库
  1330. if (conn.State != ConnectionState.Open)
  1331. {
  1332. conn.Open();
  1333. }
  1334. //创建命令
  1335. cmd = new SQLiteCommand(strCmd, conn);
  1336. //执行命令
  1337. //SQLiteDataReader sr = cmd.ExecuteReader();
  1338. da = new SQLiteDataAdapter(cmd);
  1339. da.Fill(tab);
  1340. da.Dispose();
  1341. //释放资源
  1342. conn.Close();
  1343. cmd.Dispose();
  1344. return true;
  1345. }
  1346. catch (Exception ex)
  1347. {
  1348. LogHelper.WriteLogError("检索数据库时出错!", ex);
  1349. return false;
  1350. }
  1351. }
  1352. /// <summary>
  1353. /// 检查是否存在包含特定字符串的记录
  1354. /// </summary>
  1355. /// <param name="TableName"></param>
  1356. /// <param name="ColumnName"></param>
  1357. /// <param name="searchString"></param>
  1358. /// <returns></returns>
  1359. public static bool RecordExists(string TableName, string ColumnName, string searchString,string dbPath)
  1360. {
  1361. try
  1362. {
  1363. //创建连接字符串
  1364. SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbPath));
  1365. //打开数据库
  1366. if (conn.State != ConnectionState.Open)
  1367. {
  1368. conn.Open();
  1369. }
  1370. using (SQLiteCommand command = new SQLiteCommand($"SELECT COUNT(*) FROM {TableName} WHERE {ColumnName} LIKE '%{searchString}%'", conn))
  1371. {
  1372. long count = (long)command.ExecuteScalar();
  1373. conn.Close();
  1374. conn.Dispose();
  1375. return count > 0;
  1376. }
  1377. }
  1378. catch (Exception ex)
  1379. {
  1380. LogHelper.WriteLogError($"检查是否存在包含特定字符串的记录时出错", ex);
  1381. return false;
  1382. }
  1383. }
  1384. /// <summary>
  1385. /// 检测表中是否存在列
  1386. /// </summary>
  1387. /// <param name="columnName"></param>
  1388. /// <param name="TableName"></param>
  1389. /// <param name="dbpath"></param>
  1390. /// <returns></returns>
  1391. public static bool IsHaveColumn(string columnName, string TableName, string dbpath)
  1392. {
  1393. try
  1394. {
  1395. using (SQLiteConnection connection = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbpath)))
  1396. {
  1397. // 打开数据库连接
  1398. connection.Open();
  1399. string query = $"PRAGMA table_info({TableName});";
  1400. // 创建命令对象
  1401. using (SQLiteCommand command = new SQLiteCommand(query, connection))
  1402. {
  1403. // 执行查询
  1404. using (SQLiteDataReader reader = command.ExecuteReader())
  1405. {
  1406. // 检查是否存在指定列
  1407. bool columnExists = false;
  1408. while (reader.Read())
  1409. {
  1410. string columnNameFromDB = reader["name"].ToString();
  1411. if (columnNameFromDB == columnName)
  1412. {
  1413. columnExists = true;
  1414. break;
  1415. }
  1416. }
  1417. // 输出结果
  1418. if (columnExists)
  1419. {
  1420. return true;
  1421. }
  1422. else
  1423. {
  1424. return false;
  1425. }
  1426. }
  1427. }
  1428. }
  1429. }
  1430. catch (Exception)
  1431. {
  1432. return false;
  1433. }
  1434. }
  1435. }
  1436. }