SQLite 的创建与编辑

时间:2023-03-09 04:00:45
SQLite 的创建与编辑

创建数据库语句

-(void)creatData

{

sqlite3 *sqlite = nil;

NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/data.file" ];

//打开数据库

int result  = sqlite3_open([filePath  UTF8String], &sqlite);

if (result !=SQLITE_OK) {

NSLog(@"创建失败!!!");

return ;

}

//创建表的SQL语句

NSString *sql = @"CREATE TABLE IF NOT EXISTS UserTable(userName text PRIMARY KEY ,password text,email text)";

//执行SQL语句

char *error;

result = sqlite3_exec(sqlite, [sql  UTF8String], NULL, NULL, &error);

if (result != SQLITE_OK) {

NSLog(@"创建数据库失败:%s",error);

return ;

}

//插如入一条数据

//INSERT OR REPLACE INTO UserTable (userName,password,email) VALUES(?,?,?);

//更新一条数据

//UPDATE UserTable set password = '' where userName = '';

//查询数据

//SELECT userName ,password,eamil FROM UserTable where username = '';

//删除数据

// DELETE FROM UserTable WHERE username ='';

//关闭数据库

sqlite3_close(sqlite);

}

**************************

-(void)editData

{

sqlite3 *sqlite = nil;

//句柄语句

sqlite3_stmt *stmt =nil;

//数据库

NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/data.file"];

int result  = sqlite3_open([filePath  UTF8String], &sqlite);

if (result !=SQLITE_OK) {

NSLog(@"打开数据库失败!!!");

return ;

}

//创建SQL 语句

NSString *sql = @" INSERT INTO UserTable (userName,password,email) VALUES (? ,?, ?)";

//编译SQL语句

sqlite3_prepare_v2(sqlite, [sql UTF8String], -1, &stmt, NULL);

NSString *userName = @"张三";

NSString *password = @"123456";

NSString *email    = @"mxyd.qq";

//绑定填充SQL语句

sqlite3_bind_text(stmt, 1, [userName UTF8String], -1, NULL);

sqlite3_bind_text(stmt, 2, [password UTF8String], -1, NULL);

sqlite3_bind_text(stmt, 3, [email UTF8String], -1, NULL);

SQL编辑语句

//执行SQL语句

result = sqlite3_step(stmt);

if (result == SQLITE_ERROR || result  == SQLITE_MISUSE) {

NSLog(@"编译数据库出错!!!");

return;

}

//关闭句柄语句

sqlite3_finalize(stmt);

//关闭数据库

sqlite3_close(sqlite);

NSLog(@"数据插入成功!!!");

}