數據庫sqlite的簡單應用

數據庫的基本概念性的問題,大家本身百度!sql

這裏實際操做代碼操做:數據庫

學習數據庫,首先對數據庫語言要了解,咱們先了解一些基本的數據庫的操做語言安全

 1 /*
 2      SQLite
 3      1.建立表、刪除表
 4      2.添加、刪除、修改、查找----數據
 5      3.經常使用的SQL語句
 6      4.建立表格 : create table student ( name text,  sex text, age integer)
 7      (建立名爲Student的表格 內容爲 name ***)
 8      
 9      1** text:字符串  2** integer : int   3** real :float   4** blob : data
10      
11      
12      建立表格的時候指定主鍵(惟一標識一條記錄的字段,不能重複):默認行數爲主鍵(不 指定)
13      create table boss (name text , age integer , number integer primary key)
14      
15      1.添加數據(往表裏面) (全部的列)
16      各個值之間要用 , 隔開   text類型要用 ''
17      insert into student values ('hehe','m',18)
18      
19      
20      2.給指定的列添加數據 :  insert into student (name,sex) values ('haha','f')
21      
22      3.刪除數據,若是根據主鍵來刪除,最多隻能刪除一條
23      delete from boss where number = 1
24      
25      
26      4.若是根據某個字段刪除數據,若是不是根據主鍵,全部這個字段同樣的記錄都會被刪掉
27      delete from boss where name = 'ppp'
28      
29      
30      修改student 表中 name = 'ppp'的數據 將它的 sex 改成 f|m
31      update  student set sex = 'f|m' where name = 'ppp'
32      
33      
34      5.查找【字段】(從student查找年齡爲19全部人得名字)
35      select name from student where age = 19
36      
37      查找一條【記錄】的信息
38      select * from student where age = 19
39      
40      查到表格的全部【記錄】
41      select * from student
42      
43      6.查找sex字段中 以f開頭的模糊  (模糊查找)
44      select * from student where sex like 'f%'
45      
46      
47      7.刪除表(boss)
48      drop table boss
49      
50      
51      要在工程使用SQLite,須要導入 libsqlite3.0.dylib 動態庫
52      
53      */

咱們接下來建立一個簡單的數據庫單例:.h文件以下多線程

 1 #import <Foundation/Foundation.h>
 2 #import <sqlite3.h>
 3 @class Student ;
 4 @interface DataBaseManager : NSObject
 5 
 6 
 7 //實例變量
 8 {
 9     //數據指針,經過指針能夠操做對應的數據庫
10     sqlite3 *dbPoint ;
11     
12 }
13 
14 //單例方法
15 +(instancetype)shareInstance;
16 
17 //多線程下保證數據庫安全的單例寫法
18 +(instancetype)shareInstanceAnotherWay;
19 
20 //GCD保證
21 +(instancetype)shareInstanceGCD;
22 
23 //打開數據庫
24 -(void)openDb;
25 
26 
27 //關閉數據庫
28 -(void)closeDb;
29 
30 
31 //建立表
32 -(void)createTable;
33 
34 //插入列
35 
36 -(void)createAlterTable;
37 
38 //刪除表
39 -(void)dropTable;
40 
41 
42 //添加數據(插入學生)
43 
44 -(void)insertStudent:(Student *)stu ;
45 
46 //寫入二進制數據
47 -(void)insertStudentAnotherPose:(Student *)stu ;
48 
49 
50 
51 //刪除數據(刪除學生)
52 
53 -(void)deleteStudent:(Student *)stu ;
54 
55 //修改信息
56 -(void)updateStudent:(Student *)stu withName:(NSString *)name ;
57 
58 //查找全部學生
59 -(NSMutableArray *)selectAllStudent;

.m文件學習

  1 #import "DataBaseManager.h"
  2 #import "Student.h"
  3 @implementation DataBaseManager
  4 
  5 
  6 /*
  7   單例對象:
  8          1.在不一樣類中經過單例方法獲取的都是一個對象
  9          2.保證多線程開發中數據庫的安全
 10          3.可使用單例來傳值
 11          4.
 12  */
 13 
 14 +(instancetype)shareInstance{
 15     //單例方法的實現
 16     
 17     //建立一個空對象
 18     static DataBaseManager *dbManger = nil ;
 19     
 20     //若是爲空,則建立一個對象
 21     if (nil == dbManger) {
 22         dbManger = [[DataBaseManager alloc]init];
 23     }
 24     
 25     
 26     
 27     return dbManger ;
 28 }
 29 
 30 
 31 
 32 //安全鎖 單例
 33 
 34 +(instancetype)shareInstanceAnotherWay{
 35     
 36     static DataBaseManager *dbManger = nil ;
 37     
 38     @synchronized(self){ //加線程鎖,線程鎖中的代碼會受到保護,保證此時沒有其它線程訪問self對象
 39         
 40         if (dbManger == nil) {
 41             
 42             dbManger = [[DataBaseManager alloc]init];
 43             
 44         }
 45         
 46     }
 47     
 48     return dbManger ;
 49 }
 50 
 51 
 52 //GCD
 53 +(instancetype)shareInstanceGCD{
 54     
 55     static DataBaseManager *dbManger = nil ;
 56     
 57     //聲明一個只執行一次的多線程
 58     static dispatch_once_t once ;
 59     
 60     dispatch_once(&once, ^{
 61        
 62         dbManger = [[DataBaseManager alloc]init];
 63     });
 64     
 65     
 66     
 67     return dbManger ;
 68 }
 69 
 70 
 71 
 72 
 73 
 74 
 75 
 76 
 77 //打開數據庫
 78 
 79 -(void)openDb{
 80     
 81     //想要打開的數據可路徑
 82     NSString *dbPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"student.db"];
 83     
 84      NSLog(@"%@",dbPath);
 85     
 86     /*
 87      參數1:想要打開的數據庫的路徑,須要的是C語言的字符串
 88      參數2:將dbPoint 指針和數據庫綁定,經過dbPoint能夠訪問該路徑下的數據庫
 89      
 90      若是該路徑下不存在對應的數據庫,系統會自動建立一個數據庫
 91      */
 92     int result = sqlite3_open(dbPath.UTF8String, &dbPoint);
 93     if (SQLITE_OK == result ) {
 94         NSLog(@"數據庫打開成功");
 95     }
 96     else
 97     {
 98         NSLog(@"數據庫打開失敗");
 99     }
100     
101 }
102 
103 
104 
105 
106 
107 //關閉數據庫
108 -(void)closeDb{
109     
110     int result = sqlite3_close(dbPoint) ;
111 
112     
113     
114     [self judgeWithResult:result action:@"關閉數據庫"];
115     
116     
117 }
118 
119 
120 -(void)judgeWithResult:(int)result action:(NSString *)actionStr{
121     
122     if (result == SQLITE_OK) {
123         NSLog(@"%@成功",actionStr);
124     }
125     else
126     {
127         NSLog(@"%@失敗",actionStr);
128     }
129     
130     
131     
132 }
133 
134 
135 
136 
137 
138 //建立表
139 -(void)createTable{
140     [self openDb];
141     NSString *sqlStr = @"create table students (name text , sex text , number integer primary key)";
142     
143      /**
144      *  參數1:要使用的是哪個數據庫
145      *  參數2:想對數據作什麼操做 SQL語句
146      *  參數3/4:系統預留的參數
147      *  參數5:錯誤信息
148      *
149      *  @return <#return value description#>
150      */
151     
152     char *error ;
153     int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, &error);
154     NSLog(@"%s",error);
155     
156     [self judgeWithResult:result action:@"建立表"];
157     
158     //銷燬指針
159     sqlite3_free(error) ;
160     
161     [self closeDb];
162     
163 }
164 
165 
166 //插入列
167 -(void)createAlterTable{
168     
169     [self openDb];
170     
171     NSString *string = @"alter table students add (image blob) ";
172     
173     char *error ;
174     
175     int result = sqlite3_exec(dbPoint, string.UTF8String, NULL, NULL, &error);
176     
177     [self judgeWithResult:result action:@"插入列"];
178     
179     sqlite3_free(error);
180     
181     [self closeDb];
182     
183     
184     
185 }
186 
187 
188 
189 //刪除表
190 
191 -(void)dropTable{
192     [self openDb];
193     
194     NSString *sqlStr = @"drop table students " ;
195     
196     char *error1 ;
197     int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, &error1);
198     NSLog(@"%s",error1);
199     
200     [self judgeWithResult:result action:@"刪除表"];
201     
202     //銷燬指針
203     sqlite3_free(error1) ;
204     
205     [self closeDb];
206 
207     
208 }
209 
210 
211 //添加學生
212 
213 -(void)insertStudent:(Student *)stu{
214     
215     [self openDb];
216     
217     NSString *sqlStr = [NSString stringWithFormat:@"insert into students values ('%@','%@',%ld)",stu.name,stu.sex,stu.number];
218     
219     char *error ;
220     
221     int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, &error);
222     
223     [self judgeWithResult:result action:@"插入學生"];
224     
225     sqlite3_free(error);
226     
227     [self closeDb];
228     
229 }
230 
231 
232 -(void)insertStudentAnotherPose:(Student *)stu{
233     
234     [self openDb];
235     
236     //跟隨指針
237     sqlite3_stmt *stmt = nil ;
238     
239     int result = sqlite3_prepare(dbPoint, "insert into students (name,sex,number,image) values (?,?,?,?)", -1, &stmt, NULL);
240     
241     if (result == SQLITE_OK) {
242         /*
243          若是SQL沒有問題,則綁定插入的數據 (寫入)
244          參數1:把柄 stmt
245          參數2:給SQL語句中的第幾個 ?賦值
246          參數3:寫入的內容
247          參數4:寫入數據的長度
248          參數5:系統預留的參數
249          */
250         
251         sqlite3_bind_text(stmt, 1, stu.name.UTF8String, -1, NULL);
252         
253         sqlite3_bind_text(stmt, 2, stu.sex.UTF8String, -1, NULL);
254         
255         sqlite3_bind_int(stmt, 3, (int)stu.number);
256         
257         /*
258          UIImage須要轉成NSData才能寫入數據庫
259          參數1:想要轉得那張圖片
260          參數2:壓縮程度(0~1),壓縮數值越大,圖片質量越低(壓縮完以後再取出來的圖片)
261          */
262         NSData *data = UIImageJPEGRepresentation(stu.image, 0.6);
263         
264         //參數3:首字節起始位置的指針
265         //參數4:二進制數據的長度,就是有多少個字節
266         sqlite3_bind_blob(stmt, 4, [data bytes], (int)data.length, NULL);
267         
268         int addResult = sqlite3_step(stmt);
269         
270         if (addResult == SQLITE_OK) {
271             
272             NSLog(@"插入學生圖片成功");
273         }
274         
275         
276     }
277     
278     sqlite3_finalize(stmt);
279     
280     [self closeDb];
281     
282 
283     
284     
285 }
286 
287 
288 
289 
290 //刪除學生
291 
292 -(void)deleteStudent:(Student *)stu{
293     
294     [self openDb];
295     
296     NSString *sqlStr = [NSString stringWithFormat:@"delete from students where number = %ld ",stu.number];
297     char *error ;
298     
299     int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, &error);
300     
301     [self judgeWithResult:result action:@"刪除學生"];
302     
303     sqlite3_free(error);
304     
305     [self closeDb];
306     
307 }
308 
309 //修改學生
310 
311 -(void)updateStudent:(Student *)stu withName:(NSString *)name{
312     
313     [self openDb];
314     
315     NSString *sqlStr = [NSString stringWithFormat:@"update students set name = '%@' where number = %ld ",stu.name ,stu.number];
316     char *error ;
317     
318     int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, &error);
319     
320     [self judgeWithResult:result action:@"修改學生"];
321     
322     sqlite3_free(error);
323     
324     [self closeDb];
325     
326 }
327 
328 
329 //查找全部學生
330 -(NSMutableArray *)selectAllStudent{
331     
332     [self openDb];
333     
334     NSMutableArray *stuArray = [NSMutableArray array];
335     
336     NSString *sqlStr = @"select * from students" ;
337     
338     //建立指針(數據庫的狀態指針,數據庫執行語句的全部結果都保存在這個指針裏面)
339     sqlite3_stmt *stmt= nil ;
340     /*
341      *執行SQL語句,而且將執行結果保存在stmt中
342      參數1:數據庫指針
343      參數2:要執行的SQL語句
344      參數3:限制SQL語句的長度,-1就是不限制
345      參數4:stmt指針
346      參數5:
347      */
348     int result = sqlite3_prepare(dbPoint, sqlStr.UTF8String, -1, &stmt, NULL);
349     
350     if (result == SQLITE_OK) {
351         
352         //遍歷stmt中的數據,一行一行的遍歷
353         while (sqlite3_step(stmt) == SQLITE_ROW) {
354             
355             Student *stu = [[Student alloc]init];
356             
357             /*
358              參數1:狀態指針
359              參數2:去第幾列的值(從0開始計數)
360              */
361             
362             const unsigned char *nameChar = sqlite3_column_text(stmt, 0);
363             
364             //將C語言的字符串轉化爲OC字符串
365             NSString *name = [NSString stringWithUTF8String:(const char *)nameChar];
366             
367             stu.name = name ;
368             
369             stu.sex = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)];
370             
371             stu.number = sqlite3_column_int(stmt, 2) ;
372             
373             //數據庫取出的  sqlite3_column_blob(stmt, 3)的二進制數據 是 const void * 類型 要轉化爲NSData類型
374             stu.image = [UIImage imageWithData:[NSData dataWithBytes:sqlite3_column_blob(stmt, 3) length:1]];
375             
376             [stuArray addObject:stu];
377             
378             [stu release];
379         }
380         
381     }
382     //保證同一時間只有一個
383     sqlite3_finalize(stmt) ;
384     
385     [self closeDb];
386     
387     return stuArray ;
388     
389     
390 }

 動動手調用看看效果:spa

 1 -(void)initSQLite{
 2     
 3     //初始化一個單例對象
 4     DataBaseManager *dbManager = [DataBaseManager shareInstance];
 5     
 6     //打開數據庫
 7 //    [dbManager openDb];
 8     
 9     //關閉數據庫
10 //    [dbManager closeDb];
11     
12     //建立表格
13     [dbManager createTable];
14     
15     //刪除表格
16 //    [dbManager dropTable];
17     
18     //插入列
19     [dbManager createAlterTable];
20     
21     //初始化對象
22 //    Student *stu = [[Student alloc]initWithName:@"小明" Sex:@"男" Number:18];
23 //    [dbManager insertStudent:stu];
24 //    
25 //    Student *stu1 = [[Student alloc]initWithName:@"小強" Sex:@"女" Number:20];
26     
27     Student *stu = [[Student alloc]initWithName:@"小明" Sex:@"" Number:28 Image:nil];
28     
29     stu.image = [UIImage imageNamed:@"06.jpg"];
30     
31     //插入學生
32     [dbManager insertStudent:stu];
33     
34     //寫入二進制數據
35     [dbManager insertStudentAnotherPose:stu];
36     
37     //刪除學生
38 //    [dbManager deleteStudent:stu];
39     
40     //更新
41 //    [dbManager updateStudent:stu withName:@"小明"];
42     
43     //查詢
44 //    NSArray *array = [dbManager selectAllStudent];
45 //    
46 //    for (Student *stu in array) {
47 //        NSLog(@"%@ %@ %ld",stu.name,stu.sex,stu.number);
48 //    }
49     
50 }
相關文章
相關標籤/搜索