iOS学习笔记16-SQLite应用
?/**
?? ? *
? ? ?
?? ? 應用數據庫步驟:
?? ? 1,sqlite3_open:打開或者創建數據庫并做連接操作
?? ? 2,用sql語句,創建數據庫
?? ? 3,無返回值時,用exec語句操作執行數據庫語句
?? ? 4,有返回值時,用prepare語句查詢函數,結果集遍歷得到結果,遍歷語句sqlite_step(stmt) == SQLITE_ROW
?? ? 5,將記錄中的字段解成字句 sqlite_column_XXX (結果集,字段的索引值)
?? ? **/
?
?
?
首先引用sqlite3數據庫文件
?
取到文件夾路徑
?NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
? ? NSLog(@"%@",document);
?
要創建數據庫的路徑
? ??NSString *dbFilePath = [document stringByAppendingString:@"/db.sqlite"];
?
??/**
?? ? *創建數據庫
?? ? **/
?sqlite3 *db;//與底層數據庫的連接
? ? if (sqlite3_open([dbFilePath UTF8String], &db) == SQLITE_OK) {//打開數據庫成功選擇宏的名字//此處表示創建成功
? ? ? ? NSLog(@"創建數據庫成功");
? ? }
/**
?? ? *在數據庫里面添加數據
?? ? **/
? ? NSString *createTableSql = @"create table Stu3(id integer primary key autoincrement,name text,password text)";//創建表的sq語句
? ? if(sqlite3_exec(db, [createTableSql UTF8String], NULL, NULL, NULL) == SQLITE_OK)
? ? {
?? ? ? ? ? NSLog(@"創建表成功");
?? ? ? }//執行創建表的語句
?? ?
/**
?? ? *插入數據
?? ? **/
? ? NSString *insertSql = @"insert into Stu3(name,password) values('hahah','567')";//插入數據的字符串
? ? if ( sqlite3_exec(db, [insertSql UTF8String], NULL, NULL, NULL) == SQLITE_OK) {
? ? ? ? NSLog(@"執行插入語句成功");
? ? }
?
/**
?? ? *插入多條數據
?? ? 用戶名 dsn1-10
?? ? 密碼 六位數字
?? ? **/
? ? for (int i = 0; i<10; i++) {
? ? ? ? insertSql = [NSString stringWithFormat:@"insert into Stu3(name,password) values('dsn%d','%06d')",i+1,arc4random()%100000];
//? ? ? ? NSLog(@"%@",insertSql);
?? ? ? ?
?? ? ? ?
? ? ? ? if (sqlite3_exec(db, [insertSql UTF8String], NULL, NULL, NULL)==SQLITE_OK) {
? ? ? ? ? ? NSLog(@"插入多條數據成功");
? ? ? ? }
?? ? ? ?
? ? }
?
??/**
?? ? *查詢語句
?? ? **/
? ? NSString *selectSql = @"select *from Stu3";
? ? sqlite3_stmt *stmt;//第四個參數 返回結果集
? ? sqlite3_prepare_v2(db, [selectSql UTF8String], -1, &stmt, NULL);//執行有返回值的SQL語句
? ? //遍歷結果集//把結果集一行行拿出來//宏表示如果行存在就一直做查詢
? ? while (sqlite3_step(stmt) == SQLITE_ROW) {
? ? ? ? int stu3Id = sqlite3_column_int(stmt, 0);
? ? ? ? char *stu3Name = (char *)sqlite3_column_text(stmt, 1);
? ? ? ? char *stu3PassWord = (char *)sqlite3_column_text(stmt, 2);
?? ? ? ?
? ? ? ? NSLog(@"id=%d,name=%s,password=%s",stu3Id,stu3Name,stu3PassWord);
? ? }
?
結果:
?
?
插入模型數據
//? ? for (int i =0; i<10 ; i++) {
//? ? ? ? NSString *addStr = @"insert into stu(username,userPass) values(?,?)";
//
//? ? ? ? if (sqlite3_prepare_v2(db, [addStr UTF8String], -1, NULL, NULL)==SQLITE_OK) {
//? ? ? ? ? ? sqlite3_bind_text(stmt, 1, [s.stuname UTF8string], -1, NULL);
//
//? ? ? ? ? ? if? (sqlite3_step(stmt)==SQLITE_DONE){
//? ? ? ? ? ? ? ? NSLog(@"插入數據成功");
// ? ? ? ? ? ?
//? ? ? ? ? ? }
//? ? ? ? }
//? ? }
?
轉載于:https://www.cnblogs.com/adodo/p/5209227.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的iOS学习笔记16-SQLite应用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: #pragma execution_ch
- 下一篇: 混合使用Azure LB和ILB访问相同