我正在开发使用本地数据库作为sqlite的应用程序。
我想为sqlite创建自定义文件我不知道该怎么做。
任何帮助都将不胜感激。
答案 0 :(得分:0)
首先将以下文件添加到您的项目中。
https://github.com/ConnorD/simple-sqlite
然后在项目中创建database.sqlite文件。数据库包含用户第一个nam,姓氏和个人资料picutre。
将以下代码添加到AppDelegate文件中。
- (void)createEditableCopyOfDatabaseIfNeeded
{
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"testing" message:@"path for database" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
// [alert show];
// [alert release];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"Category_DB.sqlite"];
//NSLog(@"Default writableDBPath: %@",writableDBPath);
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Category_DB.sqlite"];
//NSLog(@"Default : %@",defaultDBPath);
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
// NSLog(@"Success");
if (!success) {
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
将此方法称为didFinishLaunchingWithOptions
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self createEditableCopyOfDatabaseIfNeeded];
return NO;
}
现在将以下代码写入您想要使用查询的视图控制器中。
-(void)databaseOpen
{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [path objectAtIndex:0];
NSString *myDBnew = [documentsDirectory stringByAppendingPathComponent:@"Category_DB.sqlite"];
myDatabase = [[Sqlite alloc] init];
[myDatabase open:myDBnew];
// NSLog(@"database opened");
}
对于选择查询:
[self databaseOpen];
NSString *query_fetch=[NSString stringWithFormat:@"select Max(session_id) from Report"];
NSMutableArray *userData=[[myDatabase executeQuery:query_fetch]mutableCopy];
如果您想将图像保存到数据库
-(NSString *) getImagePath{
/* *** Modify on 16 01 2012 by Prerak *** */
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError *error;
[[NSFileManager defaultManager] createDirectoryAtPath:documentsDirectory withIntermediateDirectories:YES attributes:nil error:&error];
return documentsDirectory;
}
如果您想将图像添加到数据库
arrProfilepic = [[NSMutableArray alloc]init];
NSError *error = nil;
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath: stringPath error:&error];
NSLog(@"File Path Array is %@",filePathsArray);
for(int i=0;i<[filePathsArray count];i++)
{
NSString *strFilePath = [filePathsArray objectAtIndex:i];
if ([[strFilePath pathExtension] isEqualToString:@"jpg"] || [[strFilePath pathExtension] isEqualToString:@"png"] || [[strFilePath pathExtension] isEqualToString:@"PNG"])
{
NSString *imagePath = [[stringPath stringByAppendingString:@"/"] stringByAppendingString:strFilePath];
NSData *data = [NSData dataWithContentsOfFile:imagePath];
//NSLog(@"Data %@", data);
if(data)
{
UIImage *image = [UIImage imageWithData:data];
NSLog(@"Image %@", image);
[arrProfilepic addObject:image];
}
}
}
NSLog(@"profile is %@",arrProfilepic);
对于插入查询:
NSString *documentsDirectory = [self getImagePath];//save image to database
NSString *imagePath;
imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"User_%d.png",newid]];
NSString *relativePathImage1=nil;
NSArray *relativeArray=[imagePath componentsSeparatedByString:@"/Documents"];
UIImage *thumbImage;
thumbImage = [VcAddUser.portraitImageView.image imageScaledToFitSize:CGSizeMake(90, 90)];
NSData *thumbData = UIImageJPEGRepresentation(thumbImage, 1.0f);
[thumbData writeToFile:imagePath atomically:YES];
NSString *query_insert=[NSString stringWithFormat:@"Insert into UserDetails(User_id,User_fname,User_lname,User_image) values(%d,'%@','Smith','%@')",newid,VcAddUser.txtFUsername.text,relativePathImage1];
NSMutableArray *userData=[[NSMutableArray alloc]init];
userData=[[myDatabase executeQuery:query_insert];
[database close];
对于删除查询:
NSString *query_user=[NSString stringWithFormat:@" delete from UserDetails where User_id=%d",Userid];
[myDatabase executeNonQuery:query_user];
[myDatabase close];
**For Update query:**
NSString *updatequery=[NSString stringWithFormat:@"Update UserDetails set User_fname='%@',User_lname='%@', User_image='%@' where User_id=%d",txtFUsername.text,txtLUsername.text,relativePathImage1,UseridUpdate];
[myDatabase executeNonQuery:updatequery];
// NSLog(@"Query user is %@",updatequery);
[myDatabase close];
对于Web服务
-(void) CallWebservice
{
NSMutableData *responseData = [NSMutableData data];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"give your web service url"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *PostConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[self removeProgressIndicator];
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:@"Internet connection is not Available!" message:@"Check your network connectivity" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alt show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// check for response only
/*NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"%@",responseString);*/
NSError *error;
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(@"%@",results);
}