问题描述
|
我有一个应用程序,其中通过HTTP POST方法将数据发布到服务器API数据库,并以JSON格式获取响应。我想读取JSON数据并将其保存在sqlite数据库中。我已经完成了通过HTTP POST方法将数据发布到Web服务器API的操作,但是尚未读取JSON数据并将其保存在数据库中。
我创建了一个包含所有JSON数组对象的类。
这是.h文件:
#import <Foundation/Foundation.h>
//TokenID\":\"Vao13gifem\",\"isError\":false,\"ErrorMessage\":\"\",\"Result\":[{\"UserId\":\"153\",\"FirstName\":\"Rocky\",\"LastName\":\"Yadav\",\"Email\":\"rocky@itg.com\",\"ProfileImage\":null,\"ThumbnailImage\":null,\"DeviceInfoId\":\"12\"}],\"ErrorCode\":900}
//Terminating in response to SpringBoard\'s termination.
@interface Result : NSObject {
Nsstring * UserID;
Nsstring *FirstName;
Nsstring *LastName;
Nsstring *Email;
Nsstring *ProfileImage;
Nsstring *ThumbnailImage;
Nsstring *DeviceInfoId;
}
@property (nonatomic,retain) Nsstring *UserID;
@property (nonatomic,retain) Nsstring *FirstName;
@property (nonatomic,retain) Nsstring *LastName;
@property (nonatomic,retain) Nsstring *Email;
@property (nonatomic,retain) Nsstring *ProfileImage;
@property (nonatomic,retain) Nsstring *ThumbnailImage;
@property (nonatomic,retain) Nsstring *DeviceInfoId;
@end
这是.m文件
#import \"Result.h\"
@implementation Result
@synthesize UserID;
@synthesize FirstName;
@synthesize LastName;
@synthesize Email;
@synthesize ProfileImage;
@synthesize ThumbnailImage;
@synthesize DeviceInfoId;
- (void)dealloc {
[super dealloc];
[UserID release];
[FirstName release];
[LastName release];
[Email release];
[ProfileImage release];
[ThumbnailImage release];
[DeviceInfoId release];
}
@end
这是我的apicontroller.m
#import \"apicontroller.h\"
#import \"Result.h\"
#import <sqlite3.h>
#define DATABASE_NAME @\"journey.sqlite\"
#define DATABASE_TITLE @\"journey\"
@implementation apicontroller
@synthesize txtUserName;
@synthesize txtPassword;
@synthesize txtfirstName;
@synthesize txtlast;
@synthesize txtEmail;
@synthesize webData;
- (Nsstring *) getWritableDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
Nsstring *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:DATABASE_NAME];
}
-(void)createEditablecopyOfDatabaseIfNeeded
{
// Testing for existence
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,YES);
Nsstring *documentsDirectory = [paths objectAtIndex:0];
Nsstring *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DATABASE_NAME];
NSLog(@\"%@\",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:DATABASE_NAME];
success = [fileManager copyItemAtPath:defaultDBPath
toPath:writableDBPath
error:&error];
if(!success)
{
NSAssert1(0,@\"Failed to create writable database file with Message : \'%@\'.\",[error localizedDescription]);
}
}
-(void)sendRequest
{
UIDevice *device = [UIDevice currentDevice];
Nsstring *udid = [device uniqueIdentifier];
Nsstring *sysname = [device systemName];
Nsstring *sysver = [device systemVersion];
Nsstring *model = [device model];
NSLog(@\"idis:%@\",[device uniqueIdentifier]);
NSLog(@\"system nameis :%@\",[device systemName]);
NSLog(@\"System version is:%@\",[device systemVersion]);
NSLog(@\"System model is:%@\",[device model]);
NSLog(@\"device orientation is:%d\",[device orientation]);
Nsstring *post = [Nsstring stringWithFormat:@\"Loginkey=%@&Password=%@&DeviceCode=%@&Firmware=%@&IMEI=%@\",txtUserName.text,txtPassword.text,model,sysver,udid];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
Nsstring *postLength = [Nsstring stringWithFormat:@\"%d\",[postData length]];
NSLog(@\"%@\",postLength);
NSMutableuRLRequest *request = [[[NSMutableuRLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@\"http://192.168.0.68:91/journeyMapperAPI?RequestType=Login\"]];
[request setHTTPMethod:@\"POST\"];
[request setValue:postLength forHTTPHeaderField:@\"Content-Length\"];
[request setValue:@\"application/x-www-form-urlencoded\" forHTTPHeaderField:@\"Content-Type\"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(@\"%@\",webData);
}
else
{
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
Nsstring *loginStatus = [[Nsstring alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(@\"%@\",loginStatus);
Nsstring *json_string = [[Nsstring alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
NSArray *values = [result objectForKey:@\"Result\"];
NSMutableArray *results = [[NSMutableArray alloc] init];
for (int index = 0; index<[values count]; index++) {
NSMutableDictionary * value = [values objectAtIndex:index];
Result * result = [[Result alloc] init];
result.UserID = [value objectForKey:@\"UserId\"];
result.FirstName = [value objectForKey:@\"FirstName\"];
result.LastName =[value objectForKey:@\"LastName\"];
result.Email =[value objectForKey:@\"Email\"];
result.ProfileImage =[value objectForKey:@\"ProfileImage\"];
result.ThumbnailImage =[value objectForKey:@\"ThumbnailImage\"];
result.DeviceInfoId =[value objectForKey:@\"DeviceInfoId\"];
[results addobject:result];
[result release];
}
for (int index = 0; index<[results count]; index++) {
Result * result = [results objectAtIndex:index];
//save the object variables to database here
[self createEditablecopyOfDatabaseIfNeeded];
Nsstring *filePath = [self getWritableDBPath];
sqlite3 *database;
if(sqlite3_open([filePath UTF8String],&database) == sqlITE_OK) {
const char *sqlStatement = \"insert into Userinformation(UserID,deviceid,FirstName,Email,) VALUES (?,?,?)\";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database,sqlStatement,-1,&compiledStatement,NULL) == sqlITE_OK) {
sqlite3_bind_text( compiledStatement,1,[result.UserID UTF8String],sqlITE_TRANSIENT);
sqlite3_bind_text(compiledStatement,2,[result.DeviceInfoId UTF8String],sqlITE_TRANSIENT);
sqlite3_bind_text (compiledStatement,3,[result.FirstName UTF8String],4,[result.Email UTF8String],sqlITE_TRANSIENT);
}
if(sqlite3_step(compiledStatement) != sqlITE_DONE ) {
NSLog( @\"Save Error: %s\",sqlite3_errmsg(database) );
}
else {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@\"UIAlertView\" message:@\"Record added\" delegate:self cancelButtonTitle:@\"OK\" otherButtonTitles:nil];
[alert show];
[alert release];
alert = nil;
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
[loginStatus release];
[connection release];
[webData release];
}
-(IBAction)click:(id)sender
{
[self sendRequest];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[txtfirstName resignFirstResponder];
[txtlast resignFirstResponder];
[txtUserName resignFirstResponder];
[txtPassword resignFirstResponder];
[txtEmail resignFirstResponder];
}
// Implement viewDidLoad to do additional setup after loading the view,typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
//[self sendRequest];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotatetoInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn\'t have a superview.
[super didReceiveMemoryWarning];
// Release any cached data,images,etc. that aren\'t in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end
在connectionFinishLoading方法中,它不比较每个对象,而是直接在NSLog中输出错误:
(保存错误:near \“)\”:语法错误);
如何解决此错误?
解决方法
我的猜测是您的SQL语句的列列表中的结尾逗号引起错误:
const char *sqlStatement = \"insert into UserInformation(UserID,DeviceId,FirstName,Email,) VALUES (?,?,?)\";
请注意,Email
和)
之间有一个逗号。
尝试:
const char *sqlStatement = \"insert into UserInformation(UserID,Email) VALUES (?,?)\";
代替。