ActionMesSqliteDataClass.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.SQLite;
  4. using System.IO;
  5. using CCDCount.MODEL.ShuLiModel; // 确保引用ActiveObjectClass所在命名空间
  6. namespace CCDCount.DLL.SqlDataClass
  7. {
  8. public class ActionMesSqliteDataClass
  9. {
  10. private string DatabaseFile;
  11. private readonly string _connectionString;
  12. private object locker = new object();
  13. public ActionMesSqliteDataClass(string dbPath)
  14. {
  15. DatabaseFile = dbPath;
  16. _connectionString = $"Data Source={DatabaseFile};Version=3;"+
  17. "Journal Mode=WAL;" + // 使用WAL模式提高并发性
  18. "Synchronous=Normal;" + // 平衡性能和安全性
  19. "Cache Size=10000;" + // 增加缓存大小
  20. "Pooling=true;" + // 启用连接池
  21. "Max Pool Size=100;"; // 设置最大连接池大小
  22. string directoryPath = Path.GetDirectoryName(DatabaseFile);
  23. if (!Directory.Exists(directoryPath))
  24. {
  25. // 创建文件夹
  26. Directory.CreateDirectory(directoryPath);
  27. }
  28. InitializeDatabase();
  29. }
  30. private void InitializeDatabase()
  31. {
  32. if (!File.Exists(DatabaseFile))
  33. {
  34. SQLiteConnection.CreateFile(DatabaseFile);
  35. }
  36. using (var conn = new SQLiteConnection(_connectionString))
  37. {
  38. conn.Open();
  39. // 创建主表
  40. const string createActiveObjectTable = @"
  41. CREATE TABLE IF NOT EXISTS ActiveObject (
  42. Id INTEGER PRIMARY KEY AUTOINCREMENT,
  43. Num INTEGER NOT NULL,
  44. MinStartCol INTEGER NOT NULL,
  45. MaxEndCol INTEGER NOT NULL,
  46. LastSeenLineStartCol INTEGER NOT NULL,
  47. LastSeenLineEndCol INTEGER NOT NULL,
  48. StartLine INTEGER NOT NULL,
  49. LastSeenLine INTEGER NOT NULL,
  50. StartCheckTime TEXT NOT NULL,
  51. EndCheckTime TEXT NOT NULL,
  52. Area INTEGER NOT NULL,
  53. MaxLength REAL NOT NULL,
  54. ChannelNO INTEGER NOT NULL,
  55. ImageWidth INTEGER NOT NULL,
  56. StateCode INTEGER NOT NULL DEFAULT -1,
  57. BatchNumber TEXT NOT NULL,
  58. hasSignificantConcavity INTEGER CHECK (hasSignificantConcavity IN (0, 1)),
  59. concavityRatio REAL NOT NULL
  60. )";
  61. // 创建从表
  62. const string createRowDataTable = @"
  63. CREATE TABLE IF NOT EXISTS RowData (
  64. Id INTEGER PRIMARY KEY AUTOINCREMENT,
  65. ActiveObjectId INTEGER NOT NULL,
  66. RowsCol INTEGER NOT NULL,
  67. StartCol INTEGER NOT NULL,
  68. EndCol INTEGER NOT NULL,
  69. FOREIGN KEY (ActiveObjectId)
  70. REFERENCES ActiveObject(Id) ON DELETE CASCADE
  71. )";
  72. using (var cmd = new SQLiteCommand(conn))
  73. {
  74. cmd.CommandText = createActiveObjectTable;
  75. cmd.ExecuteNonQuery();
  76. cmd.CommandText = createRowDataTable;
  77. cmd.ExecuteNonQuery();
  78. }
  79. }
  80. }
  81. // 插入ActiveObjectClass对象及其关联数据
  82. public void InsertActiveObject(ActiveObjectClass activeObject)
  83. {
  84. lock (locker)
  85. {
  86. using (var conn = new SQLiteConnection(_connectionString))
  87. {
  88. conn.Open();
  89. using (var transaction = conn.BeginTransaction())
  90. {
  91. try
  92. {
  93. // 插入主表数据
  94. const string insertActiveObject = @"
  95. INSERT INTO ActiveObject (
  96. Num, MinStartCol, MaxEndCol, LastSeenLineStartCol,
  97. LastSeenLineEndCol, StartLine, LastSeenLine,
  98. StartCheckTime, EndCheckTime, Area, MaxLength,
  99. ChannelNO, ImageWidth, StateCode, BatchNumber,
  100. hasSignificantConcavity,concavityRatio
  101. ) VALUES (
  102. @Num, @MinStartCol, @MaxEndCol, @LastSeenLineStartCol,
  103. @LastSeenLineEndCol, @StartLine, @LastSeenLine,
  104. @StartCheckTime, @EndCheckTime, @Area, @MaxLength,
  105. @ChannelNO, @ImageWidth, @StateCode, @BatchNumber,
  106. @hasSignificantConcavity,@concavityRatio
  107. ); SELECT last_insert_rowid();";
  108. using (var cmd = new SQLiteCommand(insertActiveObject, conn))
  109. {
  110. cmd.Parameters.AddWithValue("@Num", activeObject.Num);
  111. cmd.Parameters.AddWithValue("@MinStartCol", activeObject.MinStartCol);
  112. cmd.Parameters.AddWithValue("@MaxEndCol", activeObject.MaxEndCol);
  113. cmd.Parameters.AddWithValue("@LastSeenLineStartCol", activeObject.LastSeenLineStartCol);
  114. cmd.Parameters.AddWithValue("@LastSeenLineEndCol", activeObject.LastSeenLineEndCol);
  115. cmd.Parameters.AddWithValue("@StartLine", activeObject.StartLine);
  116. cmd.Parameters.AddWithValue("@LastSeenLine", activeObject.LastSeenLine);
  117. cmd.Parameters.AddWithValue("@StartCheckTime", activeObject.StartCheckTime.ToString("o"));
  118. cmd.Parameters.AddWithValue("@EndCheckTime", activeObject.EndCheckTime.ToString("o"));
  119. cmd.Parameters.AddWithValue("@Area", activeObject.Area);
  120. cmd.Parameters.AddWithValue("@MaxLength", activeObject.MaxLength);
  121. cmd.Parameters.AddWithValue("@ChannelNO", activeObject.ChannelNO);
  122. cmd.Parameters.AddWithValue("@ImageWidth", activeObject.ImageWidth);
  123. cmd.Parameters.AddWithValue("@StateCode", activeObject.StateCode);
  124. cmd.Parameters.AddWithValue("@BatchNumber", activeObject.BatchNumber);
  125. cmd.Parameters.AddWithValue("@hasSignificantConcavity", activeObject.hasSignificantConcavity);
  126. cmd.Parameters.AddWithValue("@concavityRatio", activeObject.concavityRatio);
  127. // 获取新插入的主键ID
  128. var activeObjectId = Convert.ToInt32(cmd.ExecuteScalar());
  129. // 插入关联的RowData
  130. InsertRowData(conn, activeObjectId, activeObject.RowsData);
  131. }
  132. transaction.Commit();
  133. }
  134. catch
  135. {
  136. transaction.Rollback();
  137. throw;
  138. }
  139. }
  140. }
  141. }
  142. }
  143. // 插入RowData数据
  144. private void InsertRowData(SQLiteConnection conn, int activeObjectId, List<RowStartEndCol> rowsData)
  145. {
  146. const string insertRowData = @"
  147. INSERT INTO RowData (
  148. ActiveObjectId, RowsCol, StartCol, EndCol
  149. ) VALUES (
  150. @ActiveObjectId, @RowsCol, @StartCol, @EndCol
  151. )";
  152. using (var cmd = new SQLiteCommand(insertRowData, conn))
  153. {
  154. foreach (var row in rowsData)
  155. {
  156. cmd.Parameters.Clear();
  157. cmd.Parameters.AddWithValue("@ActiveObjectId", activeObjectId);
  158. cmd.Parameters.AddWithValue("@RowsCol", row.RowsCol);
  159. cmd.Parameters.AddWithValue("@StartCol", row.StartCol);
  160. cmd.Parameters.AddWithValue("@EndCol", row.EndCol);
  161. cmd.ExecuteNonQuery();
  162. }
  163. }
  164. }
  165. // 根据ID查询完整对象
  166. public ActiveObjectClass GetActiveObjectById(int id)
  167. {
  168. using (var conn = new SQLiteConnection(_connectionString))
  169. {
  170. conn.Open();
  171. const string query = @"
  172. SELECT
  173. ao.*,
  174. rd.Id AS RowId, rd.RowsCol, rd.StartCol, rd.EndCol
  175. FROM ActiveObject ao
  176. LEFT JOIN RowData rd ON ao.Id = rd.ActiveObjectId
  177. WHERE ao.Id = @Id";
  178. using (var cmd = new SQLiteCommand(query, conn))
  179. {
  180. cmd.Parameters.AddWithValue("@Id", id);
  181. using (var reader = cmd.ExecuteReader())
  182. {
  183. ActiveObjectClass activeObject = null;
  184. var rowsData = new List<RowStartEndCol>();
  185. while (reader.Read())
  186. {
  187. // 只初始化主对象一次
  188. if (activeObject == null)
  189. {
  190. activeObject = new ActiveObjectClass
  191. {
  192. Num = Convert.ToInt32(reader["Num"]),
  193. MinStartCol = Convert.ToInt32(reader["MinStartCol"]),
  194. MaxEndCol = Convert.ToInt32(reader["MaxEndCol"]),
  195. LastSeenLineStartCol = Convert.ToInt32(reader["LastSeenLineStartCol"]),
  196. LastSeenLineEndCol = Convert.ToInt32(reader["LastSeenLineEndCol"]),
  197. StartLine = Convert.ToInt64(reader["StartLine"]),
  198. LastSeenLine = Convert.ToInt64(reader["LastSeenLine"]),
  199. StartCheckTime = DateTime.Parse(reader["StartCheckTime"].ToString()),
  200. EndCheckTime = DateTime.Parse(reader["EndCheckTime"].ToString()),
  201. Area = Convert.ToInt32(reader["Area"]),
  202. MaxLength = Convert.ToDouble(reader["MaxLength"]),
  203. ChannelNO = Convert.ToInt32(reader["ChannelNO"]),
  204. ImageWidth = Convert.ToInt32(reader["ImageWidth"]),
  205. StateCode = Convert.ToInt32(reader["StateCode"]),
  206. BatchNumber = reader["BatchNumber"].ToString(),
  207. RowsData = rowsData
  208. };
  209. }
  210. // 添加行数据(确保RowData记录存在)
  211. if (!reader.IsDBNull(reader.GetOrdinal("RowId")))
  212. {
  213. rowsData.Add(new RowStartEndCol
  214. {
  215. RowsCol = Convert.ToInt64(reader["RowsCol"]),
  216. StartCol = Convert.ToInt32(reader["StartCol"]),
  217. EndCol = Convert.ToInt32(reader["EndCol"])
  218. });
  219. }
  220. }
  221. return activeObject;
  222. }
  223. }
  224. }
  225. }
  226. public List<string> GetAllBatchNumber()
  227. {
  228. List<string> BatchNumbers = new List<string>();
  229. using (var conn = new SQLiteConnection(_connectionString))
  230. {
  231. conn.Open();
  232. const string query = @"SELECT DISTINCT BatchNumber FROM ActiveObject";
  233. using (var cmd = new SQLiteCommand(query, conn))
  234. {
  235. using (var reader = cmd.ExecuteReader())
  236. {
  237. while (reader.Read())
  238. {
  239. BatchNumbers.Add(reader["BatchNumber"].ToString());
  240. }
  241. }
  242. }
  243. }
  244. return BatchNumbers;
  245. }
  246. public List<ActiveObjectClass> GetActiveObjectByBatchNumber(string BatchNumber)
  247. {
  248. List<ActiveObjectClass> activeObjects = new List<ActiveObjectClass>();
  249. using (var conn = new SQLiteConnection(_connectionString))
  250. {
  251. conn.Open();
  252. const string query = @"SELECT * FROM ActiveObject WHERE BatchNumber == @BatchNumber ORDER BY Id";
  253. using (var cmd = new SQLiteCommand(query, conn))
  254. {
  255. cmd.Parameters.AddWithValue("@BatchNumber", BatchNumber);
  256. using (var reader = cmd.ExecuteReader())
  257. {
  258. while (reader.Read())
  259. {
  260. object value = reader["Id"];
  261. if (!Convert.IsDBNull(value))
  262. {
  263. activeObjects.Add(new ActiveObjectClass()
  264. {
  265. Num = Convert.ToInt32(reader["Num"]),
  266. MinStartCol = Convert.ToInt32(reader["MinStartCol"]),
  267. MaxEndCol = Convert.ToInt32(reader["MaxEndCol"]),
  268. LastSeenLineStartCol = Convert.ToInt32(reader["LastSeenLineStartCol"]),
  269. LastSeenLineEndCol = Convert.ToInt32(reader["LastSeenLineEndCol"]),
  270. StartLine = Convert.ToInt64(reader["StartLine"]),
  271. LastSeenLine = Convert.ToInt64(reader["LastSeenLine"]),
  272. StartCheckTime = DateTime.Parse(reader["StartCheckTime"].ToString()),
  273. EndCheckTime = DateTime.Parse(reader["EndCheckTime"].ToString()),
  274. Area = Convert.ToInt32(reader["Area"]),
  275. MaxLength = Convert.ToDouble(reader["MaxLength"]),
  276. ChannelNO = Convert.ToInt32(reader["ChannelNO"]),
  277. ImageWidth = Convert.ToInt32(reader["ImageWidth"]),
  278. StateCode = Convert.ToInt32(reader["StateCode"]),
  279. BatchNumber = reader["BatchNumber"].ToString(),
  280. });
  281. }
  282. }
  283. }
  284. }
  285. }
  286. return activeObjects;
  287. }
  288. // 按页码获取数据
  289. public List<ActiveObjectClass> GetActiveObjectForPage(int StartLine, int EndLine)
  290. {
  291. List<ActiveObjectClass> activeObjects = new List<ActiveObjectClass>();
  292. try
  293. {
  294. using (var conn = new SQLiteConnection(_connectionString))
  295. {
  296. conn.Open();
  297. const string query = @"
  298. SELECT
  299. ao.*,
  300. rd.Id AS RowId, rd.RowsCol, rd.StartCol, rd.EndCol
  301. FROM ActiveObject ao
  302. LEFT JOIN RowData rd ON ao.Id = rd.ActiveObjectId
  303. WHERE ao.StartLine <= @StartLine AND LastSeenLine>=@LastSeenLine ORDER BY rd.Id";
  304. using (var cmd = new SQLiteCommand(query, conn))
  305. {
  306. cmd.Parameters.AddWithValue("@StartLine", EndLine);
  307. cmd.Parameters.AddWithValue("@LastSeenLine", StartLine);
  308. using (var reader = cmd.ExecuteReader())
  309. {
  310. int NowId = -1;
  311. ActiveObjectClass activeObject = null;
  312. var rowsData = new List<RowStartEndCol>();
  313. while (reader.Read())
  314. {
  315. object value = reader["Id"];
  316. if (!Convert.IsDBNull(value))
  317. {
  318. if (NowId != Convert.ToInt32(reader["Id"]))
  319. {
  320. if (activeObject != null)
  321. {
  322. activeObjects.Add(activeObject);
  323. activeObject = null;
  324. rowsData = new List<RowStartEndCol>();
  325. }
  326. NowId = Convert.ToInt32(reader["Id"]);
  327. }
  328. // 只初始化主对象一次
  329. if (activeObject == null)
  330. {
  331. activeObject = new ActiveObjectClass
  332. {
  333. Num = Convert.ToInt32(reader["Num"]),
  334. MinStartCol = Convert.ToInt32(reader["MinStartCol"]),
  335. MaxEndCol = Convert.ToInt32(reader["MaxEndCol"]),
  336. LastSeenLineStartCol = Convert.ToInt32(reader["LastSeenLineStartCol"]),
  337. LastSeenLineEndCol = Convert.ToInt32(reader["LastSeenLineEndCol"]),
  338. StartLine = Convert.ToInt64(reader["StartLine"]),
  339. LastSeenLine = Convert.ToInt64(reader["LastSeenLine"]),
  340. StartCheckTime = DateTime.Parse(reader["StartCheckTime"].ToString()),
  341. EndCheckTime = DateTime.Parse(reader["EndCheckTime"].ToString()),
  342. Area = Convert.ToInt32(reader["Area"]),
  343. MaxLength = Convert.ToDouble(reader["MaxLength"]),
  344. ChannelNO = Convert.ToInt32(reader["ChannelNO"]),
  345. ImageWidth = Convert.ToInt32(reader["ImageWidth"]),
  346. StateCode = Convert.ToInt32(reader["StateCode"]),
  347. BatchNumber = reader["BatchNumber"].ToString(),
  348. RowsData = rowsData
  349. };
  350. }
  351. // 添加行数据(确保RowData记录存在)
  352. rowsData.Add(new RowStartEndCol
  353. {
  354. RowsCol = Convert.ToInt64(reader["RowsCol"]),
  355. StartCol = Convert.ToInt32(reader["StartCol"]),
  356. EndCol = Convert.ToInt32(reader["EndCol"])
  357. });
  358. }
  359. }
  360. if (activeObject != null)
  361. {
  362. activeObjects.Add(activeObject);
  363. activeObject = null;
  364. rowsData = new List<RowStartEndCol>();
  365. }
  366. }
  367. }
  368. }
  369. }
  370. catch(Exception ex)
  371. {
  372. Console.WriteLine($"GetActiveObjectForPage - Error:{ex.Message}");
  373. }
  374. return activeObjects;
  375. }
  376. public void GetAllActionMinStartMaxEndLine(out int Num, out int StartLine, out int EndLine)
  377. {
  378. using (var conn = new SQLiteConnection(_connectionString))
  379. {
  380. conn.Open();
  381. const string query = @"
  382. SELECT MAX(Num) AS Num, MAX(LastSeenLine) AS MaxLastSeenLine, MIN(StartLine) AS MinStartLine FROM ActiveObject";
  383. int MinStartLine = 0;
  384. int MaxLastSeenLine = 0;
  385. int StartNum = 0;
  386. using (var cmd = new SQLiteCommand(query, conn))
  387. {
  388. using (var reader = cmd.ExecuteReader())
  389. {
  390. while (reader.Read())
  391. {
  392. object value = reader["MinStartLine"];
  393. if (!Convert.IsDBNull(value))
  394. {
  395. MinStartLine = Convert.ToInt32(reader["MinStartLine"]);
  396. MaxLastSeenLine = Convert.ToInt32(reader["MaxLastSeenLine"]);
  397. StartNum = Convert.ToInt32(reader["Num"]);
  398. }
  399. }
  400. }
  401. }
  402. StartLine = MinStartLine;
  403. EndLine = MaxLastSeenLine;
  404. Num = StartNum;
  405. }
  406. }
  407. // 根据Num查询ID
  408. public int GetActiveIdByNum(int Num)
  409. {
  410. int result = -1;
  411. using (var conn = new SQLiteConnection(_connectionString))
  412. {
  413. conn.Open();
  414. const string query = @"
  415. SELECT * FROM ActiveObject WHERE Num = @Num";
  416. using (var cmd = new SQLiteCommand(query, conn))
  417. {
  418. cmd.Parameters.AddWithValue("@Num", Num);
  419. using (var reader = cmd.ExecuteReader())
  420. {
  421. var rowsData = new List<RowStartEndCol>();
  422. while (reader.Read())
  423. {
  424. object value = reader["Id"];
  425. if (!Convert.IsDBNull(value))
  426. {
  427. result = Convert.ToInt32(reader["Id"]);
  428. }
  429. }
  430. }
  431. }
  432. }
  433. return result;
  434. }
  435. }
  436. }