DB_Helper.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. //
  2. // DB_Helper.m
  3. // Texts
  4. //
  5. // Created by tongjun on 13-10-12.
  6. // Copyright (c) 2013年 tongjun. All rights reserved.
  7. //
  8. #import "DB_Helper.h"
  9. #import "Question.h"
  10. #import "DES3Util.h"
  11. #import "Migration.h"
  12. static FMDatabase *shareDataBase = nil;
  13. @interface DB_Helper ()
  14. @end
  15. @implementation DB_Helper
  16. /**
  17. 创建数据库类的单例对象
  18. */
  19. + (FMDatabase *)createDataBase {
  20. if ([[NSFileManager defaultManager] fileExistsAtPath:dataBasePath]) {
  21. }else{
  22. [DB_Helper copyFileDatabase];
  23. }
  24. //transrules.db 这个库
  25. static dispatch_once_t onceToken;
  26. dispatch_once(&onceToken, ^{
  27. shareDataBase = [FMDatabase databaseWithPath:dataBasePath];
  28. if ([shareDataBase open]) {
  29. //本地成绩表
  30. [shareDataBase executeUpdate:@"CREATE TABLE IF NOT EXISTS grades (km text, score text, startDate text, endDate text, state text, isUpload text, subject text);"];
  31. //实操学时表
  32. [shareDataBase executeUpdate:@"CREATE TABLE IF NOT EXISTS scPeriod_record (userId text, classId text, classCode text, trainNum text, maxSpeed text, mileage text, gps text, obdRotationSpeed text, obdMileage text);"];
  33. //判断字段是否存在 老学员的表中没有这个字段 这里判断添加 并赋初始值
  34. if (![shareDataBase columnExists:@"obdRotationSpeed" inTableWithName:@"scPeriod_record"]){
  35. //这个方法第一次用必进的
  36. [shareDataBase executeUpdate:[NSString stringWithFormat:@"ALTER TABLE scPeriod_record ADD obdRotationSpeed text"]];
  37. [shareDataBase executeUpdate:[NSString stringWithFormat:@"update scPeriod_record set obdRotationSpeed = '0'"]];
  38. }
  39. if (![shareDataBase columnExists:@"obdMileage" inTableWithName:@"scPeriod_record"]){
  40. //这个方法第一次用必进的
  41. [shareDataBase executeUpdate:[NSString stringWithFormat:@"ALTER TABLE scPeriod_record ADD obdMileage text"]];
  42. [shareDataBase executeUpdate:[NSString stringWithFormat:@"update scPeriod_record set obdMileage = '0'"]];
  43. }
  44. //这个是不用写的 理论学时表 数据库有
  45. [shareDataBase executeUpdate:@"CREATE TABLE IF NOT EXISTS train_record (student_id text, begin_time text, end_time text, train_time text, state text, subject text, classid text);"];
  46. if (![shareDataBase columnExists:@"subject" inTableWithName:@"train_record"]){
  47. //这个方法第一次用必进的
  48. [shareDataBase executeUpdate:[NSString stringWithFormat:@"ALTER TABLE train_record ADD subject text"]];
  49. [shareDataBase executeUpdate:[NSString stringWithFormat:@"update train_record set subject = '1'"]];
  50. }
  51. if (![shareDataBase columnExists:@"classid" inTableWithName:@"train_record"]){
  52. //这个方法第一次用必进的
  53. [shareDataBase executeUpdate:[NSString stringWithFormat:@"ALTER TABLE train_record ADD classid text"]];
  54. }
  55. // // FMDBMigrationManager 创建
  56. // FMDBMigrationManager * manager = [FMDBMigrationManager managerWithDatabaseAtPath:dataBasePath migrationsBundle:[NSBundle mainBundle]];
  57. // // sql语句添加到数组的形式,就是可以写多条。
  58. // // 版本一
  59. //// Migration * migration_1 = [[Migration alloc]initWithName:@"新增USer表" andVersion:1 andExecuteUpdateArray:@[@"create table User(name text,age integer,sex text,phoneNum text)"]];
  60. //// [manager addMigration:migration_1];
  61. // // 版本二
  62. // Migration * migration_2 = [[Migration alloc]initWithName:@"train_record表新增字段classid" andVersion:2 andExecuteUpdateArray:@[@"alter table train_record add classid text"]];
  63. // [manager addMigration:migration_2];
  64. //
  65. // // 创建版本号表
  66. // // 执行完该语句,再去我们的数据库中查看,会发现多了一个表 schema_migrations
  67. // BOOL resultState = NO;
  68. // NSError *error = nil;
  69. // if (!manager.hasMigrationsTable) {
  70. // resultState = [manager createMigrationsTable:&error];
  71. // }
  72. // // UINT64_MAX 表示升级到最高版本
  73. // resultState = [manager migrateDatabaseToVersion:UINT64_MAX progress:nil error:&error];
  74. }
  75. [shareDataBase close];
  76. });
  77. return shareDataBase;
  78. }
  79. /**
  80. 关闭数据库
  81. **/
  82. + (void)closeDataBase {
  83. if(![shareDataBase close]) {
  84. NSLog(@"数据库关闭异常,请检查");
  85. return;
  86. }
  87. }
  88. //拷贝数据库
  89. +(void)copyFileDatabase {
  90. NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,NSUserDomainMask, YES);
  91. NSString *documentsDirectory = [paths objectAtIndex:0];
  92. NSString *documentLibraryFolderPath = [documentsDirectory stringByAppendingPathComponent:dataBaseName];
  93. if ([[NSFileManager defaultManager] fileExistsAtPath:documentLibraryFolderPath]) {
  94. // NSLog(@"文件已经存在了");
  95. }else {
  96. NSString *resourceSampleImagesFolderPath =[[NSBundle mainBundle]pathForResource:@"transrules" ofType:@"db"];
  97. NSData *mainBundleFile = [NSData dataWithContentsOfFile:resourceSampleImagesFolderPath];
  98. [[NSFileManager defaultManager] createFileAtPath:documentLibraryFolderPath
  99. contents:mainBundleFile
  100. attributes:nil];
  101. }
  102. }
  103. #pragma mark 理论题目练习成绩表
  104. /**创建grade表。
  105. (sfzmhm text, km text , score text,startDate text,endDate text,subject text)
  106. */
  107. +(void)saveGrade:(Grade*)aGrade
  108. {
  109. if (!aGrade) {
  110. aGrade = [Grade new];
  111. }
  112. // NSLog(@"graScore ->%@",aGrade.graScore);
  113. if ([shareDataBase open]) {
  114. [shareDataBase executeUpdate:[NSString stringWithFormat:@"insert into grades (km,score,startDate,endDate,state,isUpload)values('%@','%@','%@','%@','0','%@')",myDelegate.subject,aGrade.graScore,aGrade.startDate,aGrade.endDate,aGrade.isUpdate]];
  115. }
  116. // NSLog(@"savePath->%@",dataBasePath);
  117. [shareDataBase close];
  118. }
  119. +(NSArray *)quearyGrade
  120. {
  121. NSMutableArray *trains=[[NSMutableArray alloc]init];
  122. shareDataBase=[DB_Helper createDataBase];
  123. if([shareDataBase open]){
  124. FMResultSet *s=[shareDataBase executeQuery:[NSString stringWithFormat:@"select * from grades where state = '0' and isUpload = '1'"]];
  125. while([s next]){
  126. Grade *train=[[Grade alloc]init];
  127. train.subject=[s stringForColumn:@"km"];
  128. train.startDate=[s stringForColumn:@"startDate"];
  129. train.endDate=[s stringForColumn:@"endDate"];
  130. train.graScore=[s stringForColumn:@"score"];
  131. [trains addObject:train];
  132. }
  133. }
  134. return trains;
  135. }
  136. +(void)updateGrade:(Grade *)aGrade{
  137. shareDataBase=[DB_Helper createDataBase];
  138. if([shareDataBase open]){
  139. [shareDataBase executeUpdate:[NSString stringWithFormat:@"update grades set state='1' where startDate='%@'",aGrade.startDate]];
  140. [shareDataBase close];
  141. }
  142. }
  143. #pragma mark 理论学时表
  144. /**
  145. 貌似不需要sfzmhm。如果用户还未登录是没有这个sfzmhm的。
  146. 在上传时,只需要搜索state为0的记录即可 全部上传。
  147. */
  148. +(void)saveTrain:(TrainRecord *)trainRecord
  149. {
  150. shareDataBase=[DB_Helper createDataBase];
  151. if ([shareDataBase open]) {
  152. //此查询有开始时间 不必用科目再查
  153. FMResultSet *s = [shareDataBase executeQuery:[NSString stringWithFormat:@"SELECT count(*) FROM train_record WHERE begin_time='%@' and student_id=%@",[DES3Util encrypt:trainRecord.beginTime],trainRecord.studentId]];
  154. int count=0;
  155. if ([s next]) {
  156. count=[[s stringForColumnIndex:0]intValue];
  157. }
  158. if (count==0) {
  159. NSString *pxkm = RQ_USER_MANAGER.currentUser.pxjd;
  160. if (pxkm.length < 1) {
  161. pxkm = @"1";
  162. }
  163. // if ([pxkm isEqualToString:@"3"]) {
  164. // pxkm = @"4";
  165. // }
  166. /// 理论计时类型一地市编号:3501,3503 (福州,莆田;在科目二,科目三可以进行科目四的理论计时)
  167. if ([RQ_SHARE_FUNCTION.theoryOfTimingTypeOneCityCodeArr containsObject:RQ_USER_MANAGER.currentUser.city] && ([pxkm isEqualToString:@"2"] || [pxkm isEqualToString:@"3"])) {
  168. pxkm = @"4";
  169. }
  170. /// 理论计时类型二地市编号:null (暂无地市;在科目二可以进行科目四的理论计时)
  171. else if ([RQ_SHARE_FUNCTION.theoryOfTimingTypeTwoCityCodeArr containsObject:RQ_USER_MANAGER.currentUser.city] && [pxkm isEqualToString:@"2"]) {
  172. pxkm = @"4";
  173. }
  174. /// 理论计时类型三地市编号:3502 (厦门;在科目三可以进行科目四的理论计时)
  175. else if ([RQ_SHARE_FUNCTION.theoryOfTimingTypeThreeCityCodeArr containsObject:RQ_USER_MANAGER.currentUser.city] && [pxkm isEqualToString:@"3"]) {
  176. pxkm = @"4";
  177. }
  178. /// 新增地市 (新增地市;默认在科目二,科目三可以进行科目四的理论计时)
  179. else if (![RQ_SHARE_FUNCTION.theoryOfTimingTypeOneCityCodeArr containsObject:RQ_USER_MANAGER.currentUser.city] && ![RQ_SHARE_FUNCTION.theoryOfTimingTypeTwoCityCodeArr containsObject:RQ_USER_MANAGER.currentUser.city] && ![RQ_SHARE_FUNCTION.theoryOfTimingTypeThreeCityCodeArr containsObject:RQ_USER_MANAGER.currentUser.city] && ([pxkm isEqualToString:@"2"] || [pxkm isEqualToString:@"3"])) {
  180. pxkm = @"4";
  181. }
  182. if (RQ_USER_MANAGER.isCykh && RQStringIsNotEmpty(RQ_USER_MANAGER.cykhPxkmStr)) {
  183. pxkm = RQ_USER_MANAGER.cykhPxkmStr;
  184. }
  185. //ning(无奈) 判断-是否是 辽宁-并且当前是科目一时,台州加的3310 温州3303
  186. NSString *citystr = @"yntms,2101,2108,3310,3303";
  187. if ([citystr rangeOfString:RQ_USER_MANAGER.currentUser.city].location != NSNotFound) {
  188. pxkm = RQ_USER_MANAGER.cykhPxkmStr;
  189. }
  190. [shareDataBase executeUpdate:[NSString stringWithFormat:@"insert into train_record (student_id,begin_time,end_time,train_time,subject,classid)values('%@','%@','%@','%@','%@', '%@')",trainRecord.studentId,[DES3Util encrypt:trainRecord.beginTime],[DES3Util encrypt:trainRecord.endTime],[DES3Util encrypt:trainRecord.trainTime],pxkm,trainRecord.classid]];
  191. } else{
  192. [shareDataBase executeUpdate:[NSString stringWithFormat:@"update train_record set end_time='%@',train_time='%@' where begin_time='%@' and student_id=%@ and classid=%@",[DES3Util encrypt:trainRecord.endTime],[DES3Util encrypt:trainRecord.trainTime],[DES3Util encrypt:trainRecord.beginTime],trainRecord.studentId, trainRecord.classid]];
  193. }
  194. [shareDataBase close];
  195. }
  196. }
  197. +(NSArray *)quearyTrain:(NSString *)stuId Subject:(NSString *)sub{
  198. //NSLog(@"quearyTrain--sub----><>%@",sub);
  199. NSMutableArray *trains=[[NSMutableArray alloc]init];
  200. shareDataBase=[DB_Helper createDataBase];
  201. if([shareDataBase open]){
  202. FMResultSet *s=[shareDataBase executeQuery:[NSString stringWithFormat:@"select * from train_record where state=0 and student_id=%@ and subject = '%@'",stuId,sub]];
  203. while([s next]){
  204. TrainRecord *train = [[TrainRecord alloc]init];
  205. train.studentId = [s stringForColumn:@"student_id"];
  206. train.beginTime = [DES3Util decrypt:[s stringForColumn:@"begin_time"]];
  207. train.endTime = [DES3Util decrypt:[s stringForColumn:@"end_time"]];
  208. train.state = [s stringForColumn:@"state"];
  209. train.trainTime = [DES3Util decrypt:[s stringForColumn:@"train_time"]];
  210. train.subject = [s stringForColumn:@"subject"];
  211. train.classid = [s stringForColumn:@"classid"];
  212. [trains addObject:train];
  213. }
  214. [shareDataBase close];
  215. }
  216. return trains;
  217. }
  218. +(void)updateTrainState:(TrainRecord *)trainRecord{
  219. shareDataBase=[DB_Helper createDataBase];
  220. if([shareDataBase open]){
  221. [shareDataBase executeUpdate:[NSString stringWithFormat:@"update train_record set state=1 where begin_time='%@' and student_id=%@",[DES3Util encrypt:trainRecord.beginTime],trainRecord.studentId]];
  222. [shareDataBase close];
  223. }
  224. }
  225. + (void)deleteTrainRecord:(TrainRecord *)trainRecord {
  226. shareDataBase = [DB_Helper createDataBase];
  227. if([shareDataBase open]){
  228. [shareDataBase executeUpdate:[NSString stringWithFormat:@"delete from train_record where end_time='%@'and train_time='%@' and begin_time='%@' and student_id=%@ and classid=%@",[DES3Util encrypt:trainRecord.endTime],[DES3Util encrypt:trainRecord.trainTime],[DES3Util encrypt:trainRecord.beginTime],trainRecord.studentId, trainRecord.classid]];
  229. [shareDataBase close];
  230. }
  231. }
  232. #pragma mark 实操计时表
  233. //scPeriod_record (userId text, classId text, classCode text, trainNum text, maxSpeed text, mileage text, gps text, obdRotationSpeed text, obdMileage text)
  234. + (void)saveSCTrainWithDic:(NSDictionary *)dic
  235. {
  236. shareDataBase=[DB_Helper createDataBase];
  237. if ([shareDataBase open]) {
  238. [shareDataBase executeUpdate:[NSString stringWithFormat:@"insert into scPeriod_record (userId,classId,classCode,trainNum,maxSpeed,mileage,gps,obdRotationSpeed,obdMileage)values(%@,'%@','%@','%@','%@','%@','%@','0','0')",RQ_USER_MANAGER.currentUser._id,dic[@"classId"],[DES3Util encrypt:dic[@"classCode"]],[DES3Util encrypt:dic[@"trainNum"]],dic[@"maxSpeed"],dic[@"mileage"],dic[@"gps"]]];
  239. [shareDataBase close];
  240. }
  241. }
  242. + (void)deleteSCTrainWithTrainNum:(NSString *)trainNum
  243. {
  244. shareDataBase=[DB_Helper createDataBase];
  245. if ([shareDataBase open]) {
  246. [shareDataBase executeUpdate:[NSString stringWithFormat:@"delete from scPeriod_record where userId = '%@' and trainNum = '%@'",RQ_USER_MANAGER.currentUser._id,[DES3Util encrypt:trainNum]]];
  247. [shareDataBase close];
  248. }
  249. }
  250. + (void)deleteSCTrainWithClassId:(NSString *)classId
  251. {
  252. shareDataBase=[DB_Helper createDataBase];
  253. if ([shareDataBase open]) {
  254. [shareDataBase executeUpdate:[NSString stringWithFormat:@"delete from scPeriod_record where userId = '%@' and classId = '%@'",RQ_USER_MANAGER.currentUser._id,classId]];
  255. [shareDataBase close];
  256. }
  257. }
  258. +(void)deleteAllSCTrain
  259. {
  260. shareDataBase=[DB_Helper createDataBase];
  261. if ([shareDataBase open]) {
  262. [shareDataBase executeUpdate:[NSString stringWithFormat:@"delete from scPeriod_record where userId = '%@'",RQ_USER_MANAGER.currentUser._id]];
  263. [shareDataBase close];
  264. }
  265. }
  266. + (NSArray *)quearySCTrainWithClassId:(NSString *)classId
  267. {
  268. NSMutableArray *scTrains = [[NSMutableArray alloc]init];
  269. shareDataBase = [DB_Helper createDataBase];
  270. if([shareDataBase open]){
  271. FMResultSet *s = [shareDataBase executeQuery:[NSString stringWithFormat:@"select * from scPeriod_record where userId = '%@' and classId = '%@'",RQ_USER_MANAGER.currentUser._id,classId]];
  272. while([s next]){
  273. //classId , classCode , trainNum , maxSpeed , mileage , gps
  274. NSMutableDictionary *dic = [NSMutableDictionary dictionary];
  275. [dic setValue:[s stringForColumn:@"classId"] forKey:@"classId"];
  276. [dic setValue:[s stringForColumn:@"maxSpeed"] forKey:@"maxSpeed"];
  277. [dic setValue:[s stringForColumn:@"mileage"] forKey:@"mileage"];
  278. [dic setValue:[s stringForColumn:@"gps"] forKey:@"gps"];
  279. [dic setValue:[s stringForColumn:@"obdRotationSpeed"] forKey:@"obdRotationSpeed"];
  280. [dic setValue:[s stringForColumn:@"obdMileage"] forKey:@"obdMileage"];
  281. [dic setValue:[DES3Util decrypt:[s stringForColumn:@"classCode"]] forKey:@"classCode"];
  282. [dic setValue:[DES3Util decrypt:[s stringForColumn:@"trainNum"]] forKey:@"trainNum"];
  283. [scTrains addObject:dic];
  284. }
  285. [shareDataBase close];
  286. }
  287. return scTrains;
  288. }
  289. + (void)changeSCTrainWithTrainNum:(NSString *)trainNum
  290. RotationSpeed:(NSString *)rotationSpeed
  291. Speed:(NSString *)speed
  292. Mileage:(NSString *)mileage{
  293. shareDataBase=[DB_Helper createDataBase];
  294. if([shareDataBase open]){
  295. [shareDataBase executeUpdate:[NSString stringWithFormat:@"update scPeriod_record set obdRotationSpeed='%@' and maxSpeed='%@' and obdMileage='%@' where trainNum='%@'",rotationSpeed,speed,mileage,[DES3Util encrypt:trainNum]]];
  296. [shareDataBase close];
  297. }
  298. }
  299. #pragma mark 实操/模拟/大车计时表
  300. //scPeriod_record (userId text, classId text, classCode text, trainNum text, maxSpeed text, mileage text, gps text)
  301. + (void)saveTrainWithDic:(NSDictionary *)dic type:(NSString *)type
  302. {
  303. shareDataBase=[DB_Helper createDataBase];
  304. if ([shareDataBase open]) {
  305. NSString *sql= [NSString stringWithFormat:@"insert into %@_record (userId,classId,classCode,trainNum,maxSpeed,mileage,gps)values(%@,'%@','%@','%@','%@','%@','%@')",type,RQ_USER_MANAGER.currentUser._id,dic[@"classId"],[DES3Util encrypt:dic[@"classCode"]],[DES3Util encrypt:dic[@"trainNum"]],dic[@"maxSpeed"],dic[@"mileage"],dic[@"gps"]];
  306. BOOL zz = [shareDataBase executeUpdate:sql];
  307. if (zz) {
  308. NSLog(@"写入成功");
  309. }else{
  310. NSLog(@"写入失败");
  311. }
  312. [shareDataBase close];
  313. }
  314. }
  315. + (void)deleteTrainWithTrainNum:(NSString *)trainNum type:(NSString *)type
  316. {
  317. shareDataBase=[DB_Helper createDataBase];
  318. if ([shareDataBase open]) {
  319. [shareDataBase executeUpdate:[NSString stringWithFormat:@"delete from %@_record where userId = '%@' and trainNum = '%@'",type,RQ_USER_MANAGER.currentUser._id,[DES3Util encrypt:trainNum]]];
  320. [shareDataBase close];
  321. }
  322. }
  323. + (void)deleteTrainWithClassId:(NSString *)classId type:(NSString *)type
  324. {
  325. shareDataBase=[DB_Helper createDataBase];
  326. if ([shareDataBase open]) {
  327. [shareDataBase executeUpdate:[NSString stringWithFormat:@"delete from %@_record where userId = '%@' and classId = '%@'",type,RQ_USER_MANAGER.currentUser._id,classId]];
  328. [shareDataBase close];
  329. }
  330. }
  331. +(void)deleteAllTrainWithType:(NSString *)type
  332. {
  333. shareDataBase=[DB_Helper createDataBase];
  334. if ([shareDataBase open]) {
  335. [shareDataBase executeUpdate:[NSString stringWithFormat:@"delete from %@_record where userId = '%@'",type,RQ_USER_MANAGER.currentUser._id]];
  336. [shareDataBase close];
  337. }
  338. }
  339. + (NSArray *)quearyTrainWithClassId:(NSString *)classId type:(NSString *)type
  340. {
  341. NSMutableArray *scTrains = [[NSMutableArray alloc]init];
  342. shareDataBase = [DB_Helper createDataBase];
  343. if([shareDataBase open]){
  344. FMResultSet *s = [shareDataBase executeQuery:[NSString stringWithFormat:@"select * from %@_record where userId = '%@' and classId = '%@'",type,RQ_USER_MANAGER.currentUser._id,classId]];
  345. NSLog(@"%@ \n FMResultSet_colounm: %d",s.query,s.columnCount);
  346. while([s next]){
  347. //classId , classCode , trainNum , maxSpeed , mileage , gps
  348. NSMutableDictionary *dic = [NSMutableDictionary dictionary];
  349. [dic setValue:[s stringForColumn:@"classId"] forKey:@"classId"];
  350. [dic setValue:[s stringForColumn:@"maxSpeed"] forKey:@"maxSpeed"];
  351. [dic setValue:[s stringForColumn:@"mileage"] forKey:@"mileage"];
  352. [dic setValue:[s stringForColumn:@"gps"] forKey:@"gps"];
  353. [dic setValue:[DES3Util decrypt:[s stringForColumn:@"classCode"]] forKey:@"classCode"];
  354. [dic setValue:[DES3Util decrypt:[s stringForColumn:@"trainNum"]] forKey:@"trainNum"];
  355. [scTrains addObject:dic];
  356. }
  357. [shareDataBase close];
  358. }
  359. return scTrains;
  360. }
  361. @end