DB_Helper.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. [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]];
  186. } else{
  187. [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]];
  188. }
  189. [shareDataBase close];
  190. }
  191. }
  192. +(NSArray *)quearyTrain:(NSString *)stuId Subject:(NSString *)sub{
  193. //NSLog(@"quearyTrain--sub----><>%@",sub);
  194. NSMutableArray *trains=[[NSMutableArray alloc]init];
  195. shareDataBase=[DB_Helper createDataBase];
  196. if([shareDataBase open]){
  197. FMResultSet *s=[shareDataBase executeQuery:[NSString stringWithFormat:@"select * from train_record where state=0 and student_id=%@ and subject = '%@'",stuId,sub]];
  198. while([s next]){
  199. TrainRecord *train = [[TrainRecord alloc]init];
  200. train.studentId = [s stringForColumn:@"student_id"];
  201. train.beginTime = [DES3Util decrypt:[s stringForColumn:@"begin_time"]];
  202. train.endTime = [DES3Util decrypt:[s stringForColumn:@"end_time"]];
  203. train.state = [s stringForColumn:@"state"];
  204. train.trainTime = [DES3Util decrypt:[s stringForColumn:@"train_time"]];
  205. train.subject = [s stringForColumn:@"subject"];
  206. train.classid = [s stringForColumn:@"classid"];
  207. [trains addObject:train];
  208. }
  209. [shareDataBase close];
  210. }
  211. return trains;
  212. }
  213. +(void)updateTrainState:(TrainRecord *)trainRecord{
  214. shareDataBase=[DB_Helper createDataBase];
  215. if([shareDataBase open]){
  216. [shareDataBase executeUpdate:[NSString stringWithFormat:@"update train_record set state=1 where begin_time='%@' and student_id=%@",[DES3Util encrypt:trainRecord.beginTime],trainRecord.studentId]];
  217. [shareDataBase close];
  218. }
  219. }
  220. + (void)deleteTrainRecord:(TrainRecord *)trainRecord {
  221. shareDataBase = [DB_Helper createDataBase];
  222. if([shareDataBase open]){
  223. [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]];
  224. [shareDataBase close];
  225. }
  226. }
  227. #pragma mark 实操计时表
  228. //scPeriod_record (userId text, classId text, classCode text, trainNum text, maxSpeed text, mileage text, gps text, obdRotationSpeed text, obdMileage text)
  229. + (void)saveSCTrainWithDic:(NSDictionary *)dic
  230. {
  231. shareDataBase=[DB_Helper createDataBase];
  232. if ([shareDataBase open]) {
  233. [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"]]];
  234. [shareDataBase close];
  235. }
  236. }
  237. + (void)deleteSCTrainWithTrainNum:(NSString *)trainNum
  238. {
  239. shareDataBase=[DB_Helper createDataBase];
  240. if ([shareDataBase open]) {
  241. [shareDataBase executeUpdate:[NSString stringWithFormat:@"delete from scPeriod_record where userId = '%@' and trainNum = '%@'",RQ_USER_MANAGER.currentUser._id,[DES3Util encrypt:trainNum]]];
  242. [shareDataBase close];
  243. }
  244. }
  245. + (void)deleteSCTrainWithClassId:(NSString *)classId
  246. {
  247. shareDataBase=[DB_Helper createDataBase];
  248. if ([shareDataBase open]) {
  249. [shareDataBase executeUpdate:[NSString stringWithFormat:@"delete from scPeriod_record where userId = '%@' and classId = '%@'",RQ_USER_MANAGER.currentUser._id,classId]];
  250. [shareDataBase close];
  251. }
  252. }
  253. +(void)deleteAllSCTrain
  254. {
  255. shareDataBase=[DB_Helper createDataBase];
  256. if ([shareDataBase open]) {
  257. [shareDataBase executeUpdate:[NSString stringWithFormat:@"delete from scPeriod_record where userId = '%@'",RQ_USER_MANAGER.currentUser._id]];
  258. [shareDataBase close];
  259. }
  260. }
  261. + (NSArray *)quearySCTrainWithClassId:(NSString *)classId
  262. {
  263. NSMutableArray *scTrains = [[NSMutableArray alloc]init];
  264. shareDataBase = [DB_Helper createDataBase];
  265. if([shareDataBase open]){
  266. FMResultSet *s = [shareDataBase executeQuery:[NSString stringWithFormat:@"select * from scPeriod_record where userId = '%@' and classId = '%@'",RQ_USER_MANAGER.currentUser._id,classId]];
  267. while([s next]){
  268. //classId , classCode , trainNum , maxSpeed , mileage , gps
  269. NSMutableDictionary *dic = [NSMutableDictionary dictionary];
  270. [dic setValue:[s stringForColumn:@"classId"] forKey:@"classId"];
  271. [dic setValue:[s stringForColumn:@"maxSpeed"] forKey:@"maxSpeed"];
  272. [dic setValue:[s stringForColumn:@"mileage"] forKey:@"mileage"];
  273. [dic setValue:[s stringForColumn:@"gps"] forKey:@"gps"];
  274. [dic setValue:[s stringForColumn:@"obdRotationSpeed"] forKey:@"obdRotationSpeed"];
  275. [dic setValue:[s stringForColumn:@"obdMileage"] forKey:@"obdMileage"];
  276. [dic setValue:[DES3Util decrypt:[s stringForColumn:@"classCode"]] forKey:@"classCode"];
  277. [dic setValue:[DES3Util decrypt:[s stringForColumn:@"trainNum"]] forKey:@"trainNum"];
  278. [scTrains addObject:dic];
  279. }
  280. [shareDataBase close];
  281. }
  282. return scTrains;
  283. }
  284. + (void)changeSCTrainWithTrainNum:(NSString *)trainNum
  285. RotationSpeed:(NSString *)rotationSpeed
  286. Speed:(NSString *)speed
  287. Mileage:(NSString *)mileage{
  288. shareDataBase=[DB_Helper createDataBase];
  289. if([shareDataBase open]){
  290. [shareDataBase executeUpdate:[NSString stringWithFormat:@"update scPeriod_record set obdRotationSpeed='%@' and maxSpeed='%@' and obdMileage='%@' where trainNum='%@'",rotationSpeed,speed,mileage,[DES3Util encrypt:trainNum]]];
  291. [shareDataBase close];
  292. }
  293. }
  294. #pragma mark 实操/模拟/大车计时表
  295. //scPeriod_record (userId text, classId text, classCode text, trainNum text, maxSpeed text, mileage text, gps text)
  296. + (void)saveTrainWithDic:(NSDictionary *)dic type:(NSString *)type
  297. {
  298. shareDataBase=[DB_Helper createDataBase];
  299. if ([shareDataBase open]) {
  300. 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"]];
  301. BOOL zz = [shareDataBase executeUpdate:sql];
  302. if (zz) {
  303. NSLog(@"写入成功");
  304. }else{
  305. NSLog(@"写入失败");
  306. }
  307. [shareDataBase close];
  308. }
  309. }
  310. + (void)deleteTrainWithTrainNum:(NSString *)trainNum type:(NSString *)type
  311. {
  312. shareDataBase=[DB_Helper createDataBase];
  313. if ([shareDataBase open]) {
  314. [shareDataBase executeUpdate:[NSString stringWithFormat:@"delete from %@_record where userId = '%@' and trainNum = '%@'",type,RQ_USER_MANAGER.currentUser._id,[DES3Util encrypt:trainNum]]];
  315. [shareDataBase close];
  316. }
  317. }
  318. + (void)deleteTrainWithClassId:(NSString *)classId type:(NSString *)type
  319. {
  320. shareDataBase=[DB_Helper createDataBase];
  321. if ([shareDataBase open]) {
  322. [shareDataBase executeUpdate:[NSString stringWithFormat:@"delete from %@_record where userId = '%@' and classId = '%@'",type,RQ_USER_MANAGER.currentUser._id,classId]];
  323. [shareDataBase close];
  324. }
  325. }
  326. +(void)deleteAllTrainWithType:(NSString *)type
  327. {
  328. shareDataBase=[DB_Helper createDataBase];
  329. if ([shareDataBase open]) {
  330. [shareDataBase executeUpdate:[NSString stringWithFormat:@"delete from %@_record where userId = '%@'",type,RQ_USER_MANAGER.currentUser._id]];
  331. [shareDataBase close];
  332. }
  333. }
  334. + (NSArray *)quearyTrainWithClassId:(NSString *)classId type:(NSString *)type
  335. {
  336. NSMutableArray *scTrains = [[NSMutableArray alloc]init];
  337. shareDataBase = [DB_Helper createDataBase];
  338. if([shareDataBase open]){
  339. FMResultSet *s = [shareDataBase executeQuery:[NSString stringWithFormat:@"select * from %@_record where userId = '%@' and classId = '%@'",type,RQ_USER_MANAGER.currentUser._id,classId]];
  340. NSLog(@"%@ \n FMResultSet_colounm: %d",s.query,s.columnCount);
  341. while([s next]){
  342. //classId , classCode , trainNum , maxSpeed , mileage , gps
  343. NSMutableDictionary *dic = [NSMutableDictionary dictionary];
  344. [dic setValue:[s stringForColumn:@"classId"] forKey:@"classId"];
  345. [dic setValue:[s stringForColumn:@"maxSpeed"] forKey:@"maxSpeed"];
  346. [dic setValue:[s stringForColumn:@"mileage"] forKey:@"mileage"];
  347. [dic setValue:[s stringForColumn:@"gps"] forKey:@"gps"];
  348. [dic setValue:[DES3Util decrypt:[s stringForColumn:@"classCode"]] forKey:@"classCode"];
  349. [dic setValue:[DES3Util decrypt:[s stringForColumn:@"trainNum"]] forKey:@"trainNum"];
  350. [scTrains addObject:dic];
  351. }
  352. [shareDataBase close];
  353. }
  354. return scTrains;
  355. }
  356. @end