pragma mark - 打开创建数据库
NSString *path = [NSString stringWithFormat:@"%@/Documents/record.rdb",NSHomeDirectory()];
_database = [[FMDatabase alloc]initWithPath:path];
if(!_database.open)
{
NSLog(@"打开数据库失败");
return;
}
pragma mark - 创建数据库中的表
-(void)testCreateTable
{
//创建表
//学生信息
// 学号sid, 姓名username, 密码password, 成绩score
NSString *sql = @"CREATE TABLE IF NOT EXISTS studentInfo(sid INTEGER,username varchar(32),password varchar(32),score INTEGER)";
//执行查询语句
//执行SELECT, 使用executeQuery
//_databse executeQuery:<#(NSString *), ...#>
//除了查询语句, 其他语句使用executeUpdate执行
BOOL b = [_databse executeUpdate:sql];
NSLog(@"Create table is %d",b);
}
pragma mark - 修改数据
-(void)testUpdateData
{
//实例: 重置密码 为 123456
NSString *username = @"asan";
NSString *newPassword = @"123456";
NSString *sql = @"UPDATE studentInfo SET password = ? WHERE username = ?";
BOOL b = [_databse executeUpdate:sql,newPassword,username];
NSLog(@"UPDATE b = %d",b);
}
pragma mark - 删除数据
-(void)testDeleteData
{
//实例: 删除pangzi这条数据
NSString *username = @"pangzi";
NSString *sql = @"DELETE FROM studentInfo WHERE username = ?";
BOOL b = [_databse executeUpdate:sql,username];
NSLog(@"DELETE b = %d",b);
}
pragma mark - 查询数据
-(void)testQueryData
{
//查询所有数据, 显示所有数据
NSString *sql = @"SELECT * FROM studentInfo";
//执行查询语句
//注意: 查询完之后返回一个结果集
// 结果集: 立即为二维数组, EXCEL表格
FMResultSet *resultSet = [_databse executeQuery:sql];
//注意: 取得每一行使用[resultSet next];
// 取到一行返回YES, 最后一行取完之后在执行返回NO
while ([resultSet next]) {
//第一行数据: 1 asan 1314 58
int sid = [resultSet intForColumn:@"sid"];
NSString *name = [resultSet stringForColumn:@"username"];
NSString *password = [resultSet stringForColumn:@"password"];
int score = [resultSet intForColumn:@"score"];
NSLog(@"sid = %d, name = %@ pass = %@, score = %d",sid,name,password,score);
}
}
pragma mark - 插入数据
-(void)testInsertData
{
int sid = 1024;
NSString *username = @"pangzi";
NSString *password = @"1315";
int score = 58;
//FMDB中?作为数据占位符, 和%d类似
NSString *sql = @"INSERT INTO studentInfo(sid,username,password,score) VALUES(?,?,?,?)";
//特别注意: ?处需要的时字符串, 其他数据转化为字符串传入
BOOL b = [_databse executeUpdate:sql,
[NSString stringWithFormat:@"%d",sid],
username,
password,
[NSString stringWithFormat:@"%d",score]];
NSLog(@"INSERT b = %d",b);
}
HTTP/1.1 200 OK Server: Tengine Date: Fri, 11 Sep 2015 01:45:12 GMT Content-Type: text/html; charset=UTF-8 Content-Length: 50928 Connection: keep-alive Vary: Accept-Encoding Pragma: no-cache Cache-Control: no-cache, no-store, must-revalidate Expires: Thu, 01 Jan 1970 00:00:00 GMT Content-Language: en-US Cache-Control: no-cache