Autoincrementation of numbers in textfield - iphone

Hello all
I am generating an application in which I am having 4 fields ( product id, product name, product price, product description).
Now I want that the product id would be generated automatically when I save my data, i.e. when I run my app the text field of product id should be generated automatically and when I click on save button this id should be incremented by one and the id of last data should be saved.
So kindly help me out.

You have to take a look on this tutorials
http://upadhyayajayiphone.blogspot.in/2012/11/insert-record-in-sqlite-table-get.html
http://www.techotopia.com/index.php/An_Example_SQLite_based_iOS_4_iPhone_Application
It contains all the operations for you. While you fetching data use SELECT MAX(product_id) from TABLE_NAME to fetch the last data.

try this way....
//fetch the MAX id
[self databaseOpen];
NSString *cc=[NSString stringWithFormat:#"Select MAX(ProductID) from Table"];
NSMutableArray *temp=[[NSMutableArray alloc]init];
temp=[[database executeQuery:cc]mutableCopy];
[database close];
Explaination I am fetching the Maximum product_id from database Table.
int Product_id;
if (temp.count!=0 && ([[temp objectAtIndex:0]valueForKey:#"MAX(ProductID)"] !=[NSNull null]))
Product_id=[[[temp objectAtIndex:0]valueForKey:#"MAX(ProductID)"]intValue]+1;
else
Product_id=1;
//fetch the MAX id
Explaination If there is no record in the Table then Product_id=1
else It will incremented by 1;
Txt_productID.text=[NSString stringwithFormat:#"%d",Product_id];
Explaination Print the Product_id in the Text Field
[self databaseOpen];
NSString *q=[NSString stringWithFormat:#"Insert into Table (NAme,Price,Description) values ('%#','%#','%#')",txt_name.text,txt_price.text,txt_des.text];
[database executeNonQuery:q];
[database close];
Explaination Save the new Record in database.

If u want to achive by NSUserDefaults, then use following code
// get total count
int count=[[NSUserDefaults standardUserDefaults]integerForKey:#"TotalIdCount"];
// on save button click increment count by one and stored it
count=count+1;
[[NSUserDefaults standardUserDefaults ] setInteger:count forKey:#"TotalIdCount"];
[[NSUserDefaults standardUserDefaults] synchronize];

Related

How to sort records of child table? Parse API

I have used Parse as a back-end(Parse API: https://parse.com). I am searching for the way to sort the records of child table.
Table structures,
User
objectId, FirstName, LastName, Age
Friend
objectId, myId, FriendId
FriendId is a pointer to User table.
Now I want to retrieve all records of Friend table where myId=X and record should be shorted based on FirstName.
Any help would be appreciated
Edit:
Sorting records at iPhone side will not work because parse providing only 1000 records at a time but my table has more than 3000 records.
I have only one way and that is fetch all the records recursively and sort them. But I am looking for way to sort records at server side instead of at client side.
Currently, there is no way to do this using Parse's built-in query API. You'll have to sort the records after pulling them. Here's an example:
PFQuery * query = [PFQuery queryWithClassName:#"Friend"];
[query includeKey:#"friendId"];
NSArray * friends = [query findObjects];
NSSortDescriptor * descriptor = [[NSSortDescriptor alloc] initWithKey:#"friendId.FirstName"
ascending:Yes];
NSArray * sortedFriends = [friends sortedArrayUsingDescriptors:#[descriptor]];
// now sorted by the first name of User
This assumes that you have the pointer to the User class set up properly

How to remove all data from table using FMDB

I want to delete all data from table in my database. I am using FMDB.And i have used this code but it will not delete data from my table.
-(BOOL) deleteAll
{
FMDatabase *db = [FMDatabase databaseWithPath:[Utility getDatabasePath]];
[db open];
BOOL success = [db executeUpdate:#"TRUNCATE TABLE customers"];
[db close];
return success;
return YES;
}
Try to use this code.
BOOL success = [db executeUpdate:#"DELETE FROM customers"];
As long as i know Sqlite does not support TRUNCATE query.
Although DELETE command will work it is slow because it selects each row and than proceeds to delete it.
If you are deleting the whole table it is better to DROP the table and than recreate it:
BOOL result = [db executeUpdate:#"DROP TABLE IF EXISTS `customers`;"];
BOOL resultTwo = [db executeUpdate:#"CREATE TABLE IF NOT EXISTS customers(name text primary key, age int)"]; //or course fields in your table will be different
Swift (for completeness sakes):
let dropTable = "DROP TABLE customers"
let result = contactDB.executeUpdate(dropTable, withArgumentsInArray: nil)
if !result {
print("Error: \(contactDB.lastErrorMessage())")
}
let createTable = "CREATE TABLE IF NOT EXISTS customers(name text primary key, age int)"
if !contactDB.executeStatements(createTable) {
print("Error: \(contactDB.lastErrorMessage())")
}
reference: truncate SQLite

SQLite add or insert value

I have a table with values. I need to add or insert value in it. For example in table exists row("exml") with value: "123", and I want to add value "4567". After that it must be "1234567", if value does not exist it must be "4567", please help me..
For This you have to first get existing data from table and then put a loop for Number of Records you got in database,
Then you can do like this,
for(int i=0;i<arrOldData.count;i++)
{
NSString *strNew;
if([[arrOldData objectAtIndex:i] objectForKey:#"exml"])
{
strNew=[[[arrOldData objectAtIndex:i] objectForKey:#"exml"] stringByAppendingString:yourNewString];
}
else
{
strNew=yourNewString;
}
//your insert statement will be here with value(strNew)
}
this is not complete code,this will just give you a brief idea of what you can do,
I hope this will help you.
Check the link it is described Creating Database, Creating Table ,
Open Database Retrieve data From the table
It will help you for inserting and retrieving values.
Creating an SQLite3 database file through Objective-C
Checkthis.

INSERT OR REPLACE does not update the record in SQLITE

I am trying to insert the record in the database and whenever I do so, it inserts the record twice in the database.
I am using the following query to do my insert:
-(void) insert {
NSString *sqlQuery = [NSString stringWithFormat:#"INSERT OR REPLACE INTO test(ID,KEY ) VALUES ('%d','%#');", test.id, test.key];
const char *insert_sql = [sqlQuery UTF8String];
sqlite3_exec(db, insert_sql, NULL, NULL, NULL);
}
It always enters duplicate records whenever I run this query. Is there a way to check if the data already exists then donot insert just update.
You're initializing the SQL string using stringWithFormat: but the string you pass is not a format string. The ? parameters are only recognized by the sqlite parser.
You can fix this either by replacing the SQL string with
// Assuming id is an int and key is a string
NSString *sqlQuery = [NSString stringWithFormat:#"INSERT OR REPLACE INTO test(ID,KEY ) VALUES (%d,%#);", test.id, test.key];
Or you need to call the sqlite prepare / bind functions to bind the parameters to the wildcards. For this see the prepare and bind documentation.
I suggest the second way, as this prevents SQL injection.
Is ID a primary key for the table, or otherwise indexed? It needs to be unique for a replacement to occur.

FMDB SQLite question: row count of a query?

does anyone know how to return the count of a query when using FMDB? If I executeQuery #"select count(*) from sometable were..." I get an empty FMResultSet back. How can I get the row count of the query? Do I need to do a query like "select * from sometable where.." and iterate through the result set? Or can I use useCount or whats the best way (in terms of performance) to do this?
Thanks!
Shorter code to accomplish the same thing:
NSUInteger count = [db intForQuery:#"SELECT COUNT(field) FROM table_name"];
Make sure to include the FMDatabaseAdditions.h header file to use intForQuery:.
try this. It works for me. Iterating all the records is not recommended.
FMResultSet *rs = [db executeQuery:#"select count(FIELD) as cnt from TABLENAME"];
while ([rs next]) {
NSLog(#"Total Records :%d", [rs intForColumn:#"cnt"]);
}
May be you should check your Where clause.
Swift 2 Example
This code snippet will print the count for you.
if let rs = db.executeQuery("SELECT COUNT(*) as Count FROM TABLE_NAME", withArgumentsInArray: nil) {
while rs.next() {
print("Total Records:", rs.intForColumn("Count"))
}
}
If it did not work, a few suggestions:
a) Look for a line in your project that says let database = or var database =. If you find one then change db to database
b) Did you change the TABLE_NAME in the Select statement to whatever your table is called?
The first one is also right but by using this method you can retrieve records and count using the same query , no headache to write another one. Just add count(*) as count to your query.
You could always just run the proper SQL statement. I do something like:
FMResultSet *rs = [database executeQuery:#"select count(*) as count from words"];
[rs next];
wordsThatExist = [rs intForColumn:#"count"];
Setting up the SQL query may be quicker and cheaper then iterating.. I believe counts are cheap.
updated for Swift 3 minor change to "int For Column"
if let rs = db.executeQuery("SELECT COUNT(*) as Count FROM TABLE_NAME", withArgumentsInArray: nil) {
while rs.next() {
print("Total Records:", rs.int(forColumn: "Count"))
}
}
updated for Swift 4 minor change in method parameter name
if let rs = db.executeQuery("SELECT COUNT(*) as Count FROM TABLE_NAME", withArgumentsIn: nil) {
while rs.next() {
print("Total Records:", rs.int(forColumn: "Count"))
}
}
Please Try Following Code, this works for me
let objManager = ModelManager.getInstance()
objManager.database?.open()
let resultSet1: FMResultSet! = sharedInstance.database!.executeQuery("SELECT COUNT(Field) FROM TableNameā€, withArgumentsInArray:nil)
if (resultSet1 != nil)
{
while resultSet1.next()
{
countRecord = Int(resultSet1.intForColumn("COUNT(Field)"))
}
}
print(countRecord)
You Will get Count of Field
If you want to know the count of the rows before make something with the result, you can even do a simple query and ask for the results columnCount that give you the number of rows and you can save one query if you really want to make something with the resultSet
FMResultSet *results = [database executeQuery:#"SELECT * from tableName"];
int numberOfRows = [results columnCount];
while ([results next]){
... do your stuff ...
}