Adding data to SQLite3 DB from within Xcode - objective-c

I am trying to add 3 pieces of data to a SQLite3 DB. With help from a tutorial, I'm almost there. Below is my code.
I am receiving what I would expect from the NSLogs. I find the DB without problem, I compile the statement to send to the DB without problem, but when the app gets to sqlite3_prepare_v2(database, sqlstatement, -1, &compliedstatement, NULL)==SQLITE_OK I am expecting the data to be added to the DB, but it isn't, and I'm also expecting to display a UIAlertView to tell the user ERROR os SUCCESS. I hope you can see what I do not.
- (IBAction)addData:(id)sender {
NSString *n = [[NSString alloc] initWithString:[name text]];
NSString *a = [[NSString alloc] initWithString:[age text]];
NSString *c = [[NSString alloc] initWithString:[color text]];
NSLog(#"%# - %# - %#",n,a,c);
[self insertDataName:n Age:a Color:c];
}
This NSLog returns the text properties as expected.
- (IBAction)hide:(id)sender {
[name resignFirstResponder];
[age resignFirstResponder];
[color resignFirstResponder];
}
- (void)viewDidLoad
{
[super viewDidLoad];
DBName = #"mydatabase.sqlite";
NSArray *documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentsPaths objectAtIndex:0];
DBPath = [documentsDir stringByAppendingPathComponent:DBName];
}
-(void)checkAndCreateDB {
BOOL Success;
NSFileManager *fileManager = [NSFileManager defaultManager];
Success = [fileManager fileExistsAtPath:DBPath];
if(Success) {
NSLog(#"DB Found");
return;
}
NSLog(#"DB Not Found");
NSString *databasePathFromApp = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:DBName];
[fileManager copyItemAtPath:databasePathFromApp toPath:DBPath error:nil];
}
This NSLog returns DB Found
-(void)insertData Name:(NSString*)n Age:(NSString*)a Color:(NSString*)c {
[self checkAndCreateDB];
sqlite3 *database;
if (sqlite3_open([DBPath UTF8String],&database)==SQLITE_OK) {
NSString *statement;
sqlite3_stmt *compliedstatement;
statement = [[NSString alloc] initWithFormat:#"insert into table1 values ('%#', '%#', '%#')",n,a,c];
const char *sqlstatement = [statement UTF8String];
NSLog(#"%#",statement);
if (sqlite3_prepare_v2(database, sqlstatement, -1, &compliedstatement, NULL)==SQLITE_OK) {
if (SQLITE_DONE!=sqlite3_step(compliedstatement)) {
NSAssert1(0, #"Error by inserting '%s'", sqlite3_errmsg(database));
UIAlertView *AlertOK = [[UIAlertView alloc] initWithTitle:#"Error!" message:#"Error by inserting" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[AlertOK show];
}
else {
UIAlertView *AlertOK = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"Data successfully inserted" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[AlertOK show];
}
}
sqlite3_finalize(compliedstatement);
}
sqlite3_close(database);
}
And the last NSLog above displays insert into table1 values ('n', 'a', 'c') as I would expect.
Something is going wrong upon insertion and I can't figure it out.
FYI the DB was created using SQLiteManager. SS below:

Ok, Are you working on a simulator or an iDevice? In iDevice, you cannot create an external SQL database (at least to my knowledge). You have to create it dynamically because of the sandboxing. "FYI the DB was created using SQLiteManager." Check on that.
If that was not the problem try changing your code from "prepare ..." to "execute"
From...
if (sqlite3_prepare_v2(database, sqlstatement, -1, &compliedstatement, NULL)==SQLITE_OK) {
if (SQLITE_DONE!=sqlite3_step(compliedstatement)) {
NSAssert1(0, #"Error by inserting '%s'", sqlite3_errmsg(database));
UIAlertView *AlertOK = [[UIAlertView alloc] initWithTitle:#"Error!" message:#"Error by inserting" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[AlertOK show];
}
else {
UIAlertView *AlertOK = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"Data successfully inserted" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[AlertOK show];
}
}
sqlite3_finalize(compliedstatement);
To...
sqlite3_exec(database, [sqlstatement UTF8String], NULL, NULL, &error);
Do a log on "error" because that is very essential.
if you wanted to pop a UIAlert do this
if (error !=nil)
//show alert for error
else
//show alert for success

Related

Send any file using xmpp in cocoa application. Is it possible?

In my chat application, I am unable to send any image or file while chat. What i tried is ---
Method 1...
NSXMLElement *body = [NSXMLElement elementWithName:#"body"];
[body setStringValue:#"Send Image Testing"];
NSXMLElement *message = [NSXMLElement elementWithName:#"message"];
[message addAttributeWithName:#"type" stringValue:#"chat"];
[message addAttributeWithName:#"to" stringValue:[jid full]];
[message addAttributeWithName:#"from" stringValue:[[xmppStream myJID] full]];
[message addChild:body];
NSImage *img = [NSImage imageNamed:#"loginLogo.png"];
NSData *imageData = [img TIFFRepresentation];
NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];
NSData *data = [imageRep representationUsingType:NSJPEGFileType properties:nil];
NSString *imgStr = [NSString encodeBase64WithData:data];
NSXMLElement *ImgAttachement = [NSXMLElement elementWithName:#"attachment"];
[ImgAttachement setStringValue:imgStr];
[message addChild:ImgAttachement];
[xmppStream sendElement:message];
I added a "xmlElement" named "attachment" in "message" xmlElement. String value of "attachment" is ImageDataString encoded in "Base64" format. But this code is sending only the text to other end(not image).
Don't know the cause of failure, may be i should send NSImage or server link of the image in place of image data.
Method 2...
I also tried "XMPPOutgoingFileTransfer" classes, with following code.
[_fileTransfer sendData:decodedData
named:#"hello"
toRecipient:[XMPPJID jidWithString:#"MYUSERNAME#chat.facebook.com/RESOURCENAME"]
description:#"Baal's Soulstone, obviously."
error:&err])
But every time this is giving the same error - Error Domain=XMPPOutgoingFileTransferErrorDomain Code=-1 "Unable to send SI offer; the recipient doesn't have the required features."
Please help, if any idea
Thanks in advance
I got it working this way-
Inside setupStrem method, set up the incoming end like this -
xmppIncomingFileTransfer = [[XMPPIncomingFileTransfer alloc] init];
xmppIncomingFileTransfer.disableIBB = NO;
xmppIncomingFileTransfer.disableSOCKS5 = NO;
[xmppIncomingFileTransfer activate:xmppStream];
[xmppIncomingFileTransfer addDelegate:self delegateQueue:dispatch_get_main_queue()];
Implement the incoming end delegate methods-
- (void)xmppIncomingFileTransfer:(XMPPIncomingFileTransfer *)sender didFailWithError:(NSError *)error
{
DDLogVerbose(#"%#: Incoming file transfer failed with error: %#", THIS_FILE, error);
}
- (void)xmppIncomingFileTransfer:(XMPPIncomingFileTransfer *)sender didReceiveSIOffer:(XMPPIQ *)offer
{
DDLogVerbose(#"%#: Incoming file transfer did receive SI offer. Accepting...", THIS_FILE);
[sender acceptSIOffer:offer];
}
- (void)xmppIncomingFileTransfer:(XMPPIncomingFileTransfer *)sender didSucceedWithData:(NSData *)data
named:(NSString *)name
{
DDLogVerbose(#"%#: Incoming file transfer did succeed.", THIS_FILE);
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:name];
[data writeToFile:fullPath options:0 error:nil];
DDLogVerbose(#"%#: Data was written to the path: %#", THIS_FILE, fullPath);
}
Incoming files will be written to the documents directory, you can update UI when it is done.
On the sending side-
if (!_fileTransfer) {
_fileTransfer = [[XMPPOutgoingFileTransfer alloc] initWithDispatchQueue:dispatch_get_main_queue()];
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[_fileTransfer activate:appDelegate.xmppStream];
_fileTransfer.disableIBB = NO;
_fileTransfer.disableSOCKS5 = NO;
[_fileTransfer addDelegate:self delegateQueue:dispatch_get_main_queue()];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:filename];
NSData *data = [NSData dataWithContentsOfFile:fullPath];
NSError *err;
if (![_fileTransfer sendData:data named:filename toRecipient:[XMPPJID jidWithString:self.contact.primaryResource.jidStr] description:#"Baal's Soulstone, obviously." error:&err]) {
DDLogInfo(#"You messed something up: %#", err);
}
Implement the outgoing delegate methods -
- (void)xmppOutgoingFileTransfer:(XMPPOutgoingFileTransfer *)sender didFailWithError:(NSError *)error
{
DDLogInfo(#"Outgoing file transfer failed with error: %#", error);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"There was an error sending your file. See the logs." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
- (void)xmppOutgoingFileTransferDidSucceed:(XMPPOutgoingFileTransfer *) sender
{
DDLogVerbose(#"File transfer successful.");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"Your file was sent successfully." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
Note that the disableIBB and disableSOCKS5 should match at both ends.
If the problem still exists, go to XMPPOutgoingFileTransfer.m and then to the method-
- (void)handleRecipientDiscoInfoQueryIQ:(XMPPIQ *)iq withInfo:(XMPPBasicTrackingInfo *)info
Then put a NSLOG/Breakpoint at this line -
hasSOCKS5 = hasSI && hasFT && hasSOCKS5;
hasIBB = hasSI && hasFT && hasIBB;
Both values should become TRUE when sending a file. Check which one is FALSE (causing the error), you will get an idea why the incoming end is sending FALSE instantly. Try to fix that.

Migrating iCloud store to local

Migration works fine on Simulator. However on a device, I see no error messages but migrated store is empty.
NSDictionary *iCloudOptions = #{
NSPersistentStoreUbiquitousContentNameKey : #"iCloudNimbleStore",
NSPersistentStoreUbiquitousContentURLKey : #"transactions_logs",
NSMigratePersistentStoresAutomaticallyOption : #YES,
NSInferMappingModelAutomaticallyOption : #YES
};
NSDictionary *localOptions = #{NSMigratePersistentStoresAutomaticallyOption : #YES,
NSInferMappingModelAutomaticallyOption : #YES
};
if (![[NSFileManager defaultManager]fileExistsAtPath:self.storeURL.path]) {
#synchronized(#"Migration")
{
// thread-safe code
if ([[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil]) {
NSLog(#"iCloud");
[self migrateStoreFromURL:[self nb_URLToStoreWithFilename:[self nb_appName]]options:iCloudOptions];
}else{
[self migrateStoreFromURL:[self nb_URLToStoreWithFilename:[NSString stringWithFormat:#"%#.sqlite", [self nb_appName]]] options:localOptions];
//
[self migrateStoreFromURL:[self nb_URLToOldStoreWithFilename] options:localOptions];
}
}
}
NSDictionary *options = #{
NSMigratePersistentStoresAutomaticallyOption:#YES
,NSInferMappingModelAutomaticallyOption:#YES
};
NSError *error = nil;
[_coordinator lock];
_store = [_coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[self storeURL] options:options error:&error];
[_coordinator unlock];
if (!_store) {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Loading Fail" message:[NSString stringWithFormat:#"Failed to add store. Error: %#", error] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
NSLog(#"Failed to add store. Error: %#", error);abort();
} else {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Loading Success" message:[NSString stringWithFormat:#"Successfully added store: %#", _store] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
NSLog(#"Successfully added store: %#", _store);
if (_store && !error) {
// Encrypt the password database
NSError *encrError;
NSDictionary *fileAttributes = [NSDictionary dictionaryWithObject:NSFileProtectionComplete forKey:NSFileProtectionKey];
if (![[NSFileManager defaultManager] setAttributes:fileAttributes ofItemAtPath:self.storeURL.path error:&encrError]){
NSLog(#"Unresolved error with password store encryption %#, %#", encrError, [encrError userInfo]);
abort();
}else {NSLog(#"Encrypted");}
}
}
Here is migration procedure:
- (void)migrateStoreFromURL:(NSURL *)oldStoreURL options:(NSDictionary *)oldOptions{
if (debug==1) {
TFLog(#"Running %# '%#'", self.class, NSStringFromSelector(_cmd));
}
if (_store)
{
NSLog(#"NOT NEEDED");
return;
}
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Migration" message:[NSString stringWithFormat:#"Found old store at %#",oldStoreURL.path] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:self.storeURL.path]) {
NSDictionary *options =
#{
NSMigratePersistentStoresAutomaticallyOption:#YES
,NSInferMappingModelAutomaticallyOption:#YES
};
NSError *error = nil;
[_coordinator lock];
NSPersistentStore *srcPS = [_coordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:oldStoreURL
options:oldOptions
error:&error];
_store = [_coordinator migratePersistentStore:srcPS
toURL:self.storeURL
options:options
withType:NSSQLiteStoreType
error:&error];
[_coordinator unlock];
if (_store && !error) {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Migration Success" message:[NSString stringWithFormat:#"Old store successfully migrated from %#",oldStoreURL.path] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
// Encrypt the password database
NSError *encrError;
NSDictionary *fileAttributes = [NSDictionary dictionaryWithObject:NSFileProtectionComplete forKey:NSFileProtectionKey];
if (![[NSFileManager defaultManager] setAttributes:fileAttributes ofItemAtPath:self.storeURL.path error:&encrError]){
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Encryption Error" message:[NSString stringWithFormat:#"Unresolved error with password store encryption %#, %#", encrError, [encrError userInfo]] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
}else{
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Migration Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
}
Upd.: I checked size of the newly migrated store and it's 0. Most strange is that _store && !error is true. I also tried to add NSPersistentStoreRemoveUbiquitousMetadataOption: #YES to migration options but it doesn't change anything.
Upd. 2 I think that on a device iCloud store url is nil before its loaded. I need some workaround to wait until its finished.
I'm not 100% sure I understand what you are trying to do with the migrations. It is common to seed data in an empty store with a migration, but it looks like you are trying to migrate data out of iCloud into your local store. Is that right? You should not need to do that. iCloud should automatically add the data from other devices to your store.
This line also doesn't look right:
NSPersistentStoreUbiquitousContentURLKey : #"transactions_logs",
I think you want to use a URL there that points to the transaction log directory inside the iCloud container. Eg.
NSURL *containerURL = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
NSURL *url = [containerURL URLByAppendingPathComponent:#"transactions_logs"];
When working with iCloud, it is important to realize that data does not transfer instantaneously. It can take a while to arrive, and your app doesn't really have any way to know for sure if there is data coming. You can monitor metadata with metadata queries, but even that often arrives some time after data on other devices has already been generated.
So simply looking in the ubiquity container for data will not help much, because there may or may not be data available. You just do not know, and you have to develop your approach with that assumption in mind, so that it can handle any delays.
The migrations required to get iCloud sync working with Core Data are messy and unnecessary. You are probably much more likely to get things working well with a framework that does that stuff automatically, such as Core Data Ensembles. (Disclosure: I am the developer of Ensembles.)

Why does isEqualToString not work for NSString?

I am trying to code the login process for an iPhone app in XCode. The problem is with the NSString serverOutput below. When I print it using printf(serverOutput.UTF8String); it prints 'Yes' to the console. However when I compare serverOutput to "Yes" it doesn't work. Any help would be appreciated. Here's my code:
- (IBAction) loginButton: (id) sender
{
// TODO: spawn a login thread
indicator.hidden = FALSE;
[indicator startAnimating];
NSString *post =[NSString stringWithFormat:#"username=%#&password=%#",userName.text, password.text];
NSString *hostStr = #"http://10.243.1.184/connectDB.php?";
hostStr = [hostStr stringByAppendingString:post];
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
printf(serverOutput.UTF8String);
if([serverOutput isEqualToString:#"Yes"]){
UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:#"Congrats" message:#"You are authorized"
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertsuccess show];
[alertsuccess release];
}
else {
UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Username or Password Incorrect"
delegate:self cancelButtonTitle:#"OK"otherButtonTitles:nil, nil];
[alertsuccess show];
[alertsuccess release];
//[self.navigationController pushViewController:DashboardViewController animated:YES];
loginbutton.enabled = TRUE;
}
loginbutton.enabled = FALSE;
}
Based on helping others with similar situations I would say the problem is that the response from the server isn't just the string "Yes". Most likely there is some whitespace before and/or after the text. Perhaps a stray newline or two.
Try this:
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(#"Result = '%#'", serverOutput); // look for space between quotes
serverOutput = [serverOutput stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

how to show uialertview in another thread in objective c

I created another thread and its functionality is working well. But only case is in new thread we cannot use UIControllers. As an example I couldn't use UIAlerview in new thread. How can I slove it?
My tried code is bellow.
- (IBAction)btnCopyImage:(id)sender
{
[NSThread detachNewThreadSelector:#selector(DownloadCheck) toTarget:self withObject:nil];
// [self performSelectorOnMainThread:#selector(DownloadCheck) withObject:nil waitUntilDone:NO];
NSLog(#"My name is ");
int sum =0;
for (int i=1; i<=1000; i++)
{
sum =sum+i;
}
NSLog(#"sum %d",sum);
}
-(void)DownloadCheck
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Download"];
NSString* saveDialogURL = #"/Volumes/Inbox/7. Debugging and Troubleshooting.zip";
NSString* fileNameWithExtension = saveDialogURL.lastPathComponent;
NSLog(#"path %# ",fileNameWithExtension);
NSString *pathWithExtention=[NSString stringWithFormat:#"%#/%#", path,fileNameWithExtension];
NSLog(#"path %#",pathWithExtention);
//Remove existing file
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
NSError *error;
[filemgr removeItemAtPath:pathWithExtention error:&error];
//Copy file to i phone created directory
if ([filemgr copyItemAtPath: saveDialogURL toPath: pathWithExtention error: NULL] == YES)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Download"
message:#"Downloaded Sucessfully"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"OK", nil];
[alertView show];
NSLog (#"Copy successful");
}
else
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Download Faild"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"OK", nil];
[alertView show];
NSLog (#"Copy Faild");
}
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
[self performSelectorOnMainThread:#selector(DownloadCheck) withObject:nil waitUntilDone:NO]; this cannot be used because it's working on same thread.
So what should I do by using same code?

Insert data from text fields into SQLite database

I am trying to insert data into my SQLite database. I have imported all the neccassry frameworks and database files nedded for my project. In my controller class xib there are two textfields and a button. I want the data entered into both of the text fields saved in my database when I click on the button.
In my app delagate I have created two functions, one function to append the path of the database, and the other to insert data into the database. In the insert function, I check for certain conditions, i.e., if data gets added, an alert view should be displayed showing the record added, but when I add a new record it always goes into the else block, which is an error.
-(void)checkAndCreateDB {
NSString* databaseName = #"login.sqlite";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *databasePath=[documentsDir stringByAppendingPathComponent:#"login.sqlite"];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:databasePath];
if(success) return;
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
-(void)insertData{
sqlite3 *database;
sqlite3_stmt *statement;
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *databasePath=[documentsDir stringByAppendingPathComponent:#"login.sqlite"];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO Loginchk (uname,password) VALUES ('%#',' %#');",Gunameq,Gpassq];
const char *insert_stmt = [insertSQL UTF8String];
if(sqlite3_prepare_v2(database, insert_stmt, -1, &statement, nil)== SQLITE_OK)
{
sqlite3_bind_text(statement, 1, [Gunameq UTF8String], -1, NULL);
sqlite3_bind_text(statement, 2, [Gpassq UTF8String], -1, NULL);
}
if(sqlite3_step(statement)==SQLITE_DONE)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Add Record" message:#"Contact Added" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert=nil;
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"record" message:#"record not created" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert=nil;
}
// Release the compiled statement from memory
sqlite3_finalize(statement);
sqlite3_close(database);
}
}
This is my login controller class. Here I have declared a function through which I access my app delegate's functions.
-(IBAction)buttonPressed:(id)sender
{
Gpassq=Password.text;
Gunameq=Uname.text;
NSLog(#"%#%#",Gunameq,Gpassq);
AddListAppDelegate *appDelegate =(AddListAppDelegate *)[[UIApplication sharedApplication]delegate];
[appDelegate insertData];
}
Please solve this problem.
static sqlite3_stmt *insertStmt = nil;
if(insertStmt == nil)
{
insertSql = "INSERT INTO Loginchk (uname,password) VALUES(?,?)";
if(sqlite3_prepare_v2(database, insertSql, -1, &insertStmt, NULL) != SQLITE_OK)
NSAssert1(0, #"Error while creating insert statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_bind_text(insertStmt, 1, [Gunameq UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(insertStmt, 2, [Gpassq UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(insertStmt))
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
else
NSLog("Inserted");
//Reset the add statement.
sqlite3_reset(insertStmt);
insertStmt = nil;
In above you can see. If you are binding data no need to have stringWithFormat. Just put question marks and than bind text.
Hope it helps.
this code may be run
-(void) insert:key1:key2:key3
{
databaseName= #"db3.sqlite";
NSArray *documentPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDir=[documentPaths objectAtIndex:0];
databasePath=[documentsDir stringByAppendingPathComponent:databaseName];
sqlite3 *database;
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSString *stmnt=[[[NSString alloc]initWithFormat:#"insert into login values(\"%#\",\"%#\",\"%#\")", key1,key2,key3] autorelease];
const char *sqlStatement = [stmnt UTF8String];
sqlite3_stmt *compiledStatement;
if (sqlite3_prepare_v2(database, sqlStatement,-1, &compiledStatement,NULL) == SQLITE_OK)
{
if (SQLITE_DONE!=sqlite3_step(compiledStatement))
{
UIAlertView *al=[[UIAlertView alloc] initWithTitle:#"INFO"
message:#"Registration Fail"
delegate:self
cancelButtonTitle:#"ok"
otherButtonTitles:nil];
[al show];
[al release];
}
else {
UIAlertView *al=[[UIAlertView alloc] initWithTitle:#"INFO"
message:#"Registerd"
delegate:self
cancelButtonTitle:#"ok"
otherButtonTitles:nil];
[al show];
[al release];
}
}
sqlite3_reset(compiledStatement);
}
sqlite3_close(database);
}
-(IBAction)clicked:(id)sender
{
NSString *t1=[[NSString alloc]initWithFormat:#"%#",txt1.text];
NSString *t5=[[NSString alloc]initWithFormat:#"%#",txt2.text];
NSString *t3=[[NSString alloc]initWithFormat:#"%#",txt3.text];
//NSString *t2=[[NSString alloc]init];
//NSInteger t3;
//NSString *t3=[[NSString alloc]init];
//t1=txt1.text;
//t2=txt2.text;
//t3=txt3.text;
[self insert:t1:t5:t3];
}
another way around for insert is
// Create insert statement for the address
NSString *insertStatement = [NSString stringWithFormat:#"INSERT INTO ADDRESS (STREETNAME, STREETNUMBER, PERSONID) VALUES (\"%#\", \"%#\", \"%d\")", person.address.streetName, person.address.streetNumber, personID];
if ( sqlite3_exec(databaseHandle, [insertStatement UTF8String], NULL, NULL, &error) == SQLITE_OK)
{
NSLog(#"Person inserted.");
}
else
{
NSLog(#"Error: %s", error);
}
Try this code:
-(void)addItem{
//for saving the data into database
if(addStmt == nil) {
const char *sql = "insert into employee(name, address) Values(?, ?)";
if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
NSAssert1(0, #"Error while creating add statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_bind_text(addStmt, 1, [name UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 2, [address UTF8String], -1, SQLITE_TRANSIENT);
NSLog(#"%#",name);
NSLog(#"%#",address);
if(SQLITE_DONE != sqlite3_step(addStmt))
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
else
//SQLite provides a method to get the last primary key inserted by using sqlite3_last_insert_rowid
rowID = sqlite3_last_insert_rowid(database);
//Reset the add statement.
sqlite3_reset(addStmt);
}
+ (void) getInitialDataToDisplay:(NSString *)dbPath {
//for retrieving data from database
InsertDataAppDelegate *appDelegate = (InsertDataAppDelegate *)[[UIApplication sharedApplication] delegate];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sql = "select name, address from employee";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
//NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
Item *Obj = [[Item alloc]initWithPrimaryKey:primaryKey];
Obj.name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
Obj.address=[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
Obj.isDirty = NO;
[appDelegate.array addObject:Obj];
[Obj release];
}
}
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
- (IBAction)sbumitbuttoncliked:(id)sender
{
sqlite3 *database;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"somefile1.sqlite"];
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK)
{
sqlite3_stmt *statment = nil;
NSString *queryString = [NSString stringWithFormat:#"Insert into form1 (name,password,phoneno)values(\'%#\',\'%#\',\'%#\')",textobj1.text, textobj2.text,textobj3.text];
NSLog(#"%#",queryString);
const char *sql = [queryString UTF8String];
sqlite3_prepare_v2(database, sql, -1, &statment, NULL);
if (textobj1.text.length==0||textobj2.text.length==0||textobj3.text.length==0) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Success" message:#"Not Registered " delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil ];
[alert show];
}
else if (sqlite3_step(statment) == SQLITE_DONE)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Success" message:#"you have successfully registered" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil ];
[alert show];
[self dismissModalViewControllerAnimated:YES];
}
sqlite3_finalize(statment);
}