I have create one sqlite3 database and in that database i am writing name text but when i write in to database it doesn't write only blank row create i am doing like this
if(sqlite3_step(statement)==SQLITE_DONE)
{
NSLog(#"ALERT>TEXT===%#",alert.alertText);
NSLog(#"....");
sqlite3_bind_text(statement, 1, [alert.alertText UTF8String], -1, NULL);
sqlite3_step(statement);
NSLog(#"insertion is done");
}
if(sqlite3_open(dbPath, &db)==SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:#"INSERT INTO YourTable ('symbol') VALUES",%#];
const char *insertStmt=[insertSQL UTF8String];
char *errmsg=nil;
if(sqlite3_exec(db, insertStmt, NULL, NULL, &errmsg)==SQLITE_OK)
{
NSLog(#"Row ADDED!");
}
sqlite3_close(db);
}
Please vote and marked it as answered if it fulfills your requirement.
Thanks,
I am using this code to insert data in to my database.
NSString *sqlStatement = [NSString stringWithFormat:#"insert into TableName alertName values '%#'",[name stringWithPercentEscape]];
NSLog(#"%#",sqlStatement);
if (sqlite3_exec(database, [sqlStatement cStringUsingEncoding:NSUTF8StringEncoding], NULL, NULL, &error) == SQLITE_OK)
{
NSLog(#"record inserted successfully!!");
NSLog(#"%#",databasePath);
}
I recommend you to use the FMDB framework.It is a very light package.
With it you can manage your sqlite database just by SQL.
This is the link
Related
I have a problem with sqlite, when i select a single row from table and then check sqlite3_step(statement) == SQLITE_ROW both values are different and not getting inside while statement.
This is the code:
if (sqlite3_prepare_v2(db, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
//NSLog(#"working777.............%d",sqlite3_step(statement));
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"working888.............%d",SQLITE_ROW);
NSString *addressField = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 0)];
NSString *phoneField = [[NSString alloc] initWithUTF8String:(const char *)sqlite3_column_text(statement, 1)];
NSLog(#"............statement...........addressField %#, phoneField %#",addressField,phoneField);
}
sqlite3_finalize(statement);
}
sqlite3_close(db);
}
The proper way to create such a query would be like this:
NSString *querySQL = #"SELECT * FROM Major_Events WHERE temple_id = ?";
Then prepare the statement. I assume query_stmt is the char * value from querySQL.
Once the statement is prepared you then need to bind the value.
sqlite3_bind_int(statement, 1, temp_id); // bind is 1-based
Of course temp_id needs to be an int value and not a string. There are various sqlite3_bind_xxx statements for different data types. Use the appropriate one.
Once all of the query parameters are bound, you can execute the query using sqlite3_step.
The nice thing about this approach over string formats is that strings get properly escape and put in quotes for you. It's much harder to mess up and it makes your queries much safer against SQL injection attacks.
For many records:-
if (sqlite3_open([[self getDBPath] UTF8String], &database) == SQLITE_OK) {
const char *sql = "select * from Place";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
}
sqlite3_finalize(selectstmt);
sqlite3_close(database);
}
}
else
{
sqlite3_close(database);
}
If you want a single record then change while to if
if(sqlite3_step(selectstmt) == SQLITE_ROW) {
rest everything will be same
I hope it helps and if your while loop is not getting executed then it means there is some problem with your query.You need to check that also.
I am using ios5.0 and Xcode 4.2 and sqlite 3. I can create the database and table and also I can read and write in table.
But If i use the sqlcipher , then I got the error "a file is encrypted or is not a database" .
Please explain me, why i am getting these kind of error ?. I have attached the code with this. Please find it.. and THanks in advance.
-(void) readFromDatabase {
// Setup the database object
sqlite3 *database;
devicesArray = [[NSMutableArray alloc] init];
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "select * from patient;";
sqlite3_stmt *compiledStatement;
// const char* key = [#"test" UTF8String];
// NSLog(#"Length %lu" , strlen(key));
// sqlite3_key(database, key, strlen(key));
sqlite3_exec(database, "PRAGMA KEY='test123';", NULL, NULL, NULL);
printf( "could not prepare statemnt: %s\n", sqlite3_errmsg(database) );
int returnCode = sqlite3_exec(database, (const char*) "SELECT count(*) FROM patient;", NULL, NULL, NULL);
printf( "could not prepare statemnt: %s\n", sqlite3_errmsg(database) );
NSLog(#"%d",returnCode); // the return code is 26 and getting the error
if (sqlite3_exec(database, (const char*) "SELECT count(*) FROM patient;", NULL, NULL, NULL) == SQLITE_OK) {
NSLog(#"Success");
} else {
NSLog(#"Failure");
}
returnCode = sqlite3_prepare_v2( database, sqlStatement, -1, &compiledStatement, nil);
printf( "could not prepare statemnt1: %s\n", sqlite3_errmsg(database) );
NSLog(#"%d",returnCode); //the return code is 26 and getting the error
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aDescription = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *aImageUrl = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
devices *d = [[devices alloc] initWithName:aName description:aDescription url:aImageUrl];
[devicesArray addObject:d];
[devices release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
Your code seems to be assuming that the database already exists. Are you trying to open an existing, non-encrypted database and then encrypt it using SQLCipher? If so, what you are doing will not work.
The sqlite3_key function does not encrypt an existing database. If you want to encrypt an existing database you'd either need to ATTACH a new encrypted database and move data between the two, as described here:
http://zetetic.net/blog/2009/12/29/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher/
Or, using the SQLCipher 2 you can use sqlcipher_export which provides an easy way to move data between databases.:
http://groups.google.com/group/sqlcipher/msg/76d5b03426419761
I am trying to insert a set of values in an sqlite table using a for loop. It is inserting only one set of value. I am posting here my code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:#"myDatabase.sql"];
for(int i=0;i<[arr count];i++)
{
sqlite3 *database;
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSLog(#"\n inserting data \n");
sqlite3_exec(database, [[NSString stringWithFormat:#"INSERT INTO AnswerConnect VALUES('%#')",[arr objectAtindex:i] ] UTF8String], NULL, NULL, NULL);
//sqlite3_finalize(compiledStatement);
sqlite3_close(database);
}
}
Thanks in advance.
You have to first prepare a sqlite statement to insert data in table.Try this :
sqlite3_stmt *statement = nil
const char *sql = "insert into tablename (col1,col2) Values( ?, ?)";
if(sqlite3_prepare_v2(database, sql, -1, &statement, NULL) != SQLITE_OK)
{
NSLog(#"Error while creating add statement. '%s'", sqlite3_errmsg(database));
}
for(int i=0;i<[arr count];i++)
{
sqlite3_bind_text(statement, 1,[[arr objectAtindex:i] UTF8String] , -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(add_statement))
{
NSLog(#"Error while inserting result data. '%s'", sqlite3_errmsg(database));
}
//Reset the add statement.
sqlite3_reset(statement);
}
Don't do like that! Don't open/close SQLite connection in loop like that! Open handle to database outside from loop and than just use pointer on it. In this kind of request it's unsafe to insert format, because SQL statement may be compiled with some kind of injection code. Use sqlite3_stmt instead and bind values to it. Also if you compile only one instance of sqlite3_stmt and reuse it, this will give you better performance than compiling new statements all the time.
How many columns in each data set? Does it insert only one value from single data set like string?
I have a SQLite database that I am creating in my iOS application. A series of numbers are being stored in this database. I want to sum the entire column, and return the data to be displayed within the application.
Everything writing to the DB is working properly, but I am stuck trying to return the summed data. Any help would be greatly appreciated.
-(void) dataReturn: (NSString *) tableNamed{
NSString *myData = [NSString stringWithFormat:#"SELECT SUM(column1) AS data1 FROM myDB", tableNamed];
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(db, [myData UTF8String], -1, &statement, nil) ==SQLITE_OK){
while (sqlite3_step(statement) == SQLITE_ROW){
int *field2 = (int *) sqlite3_column_int(statement, 1);
NSString *myString =[[NSString alloc] initWithFormat:#"%#", field2];
}
}
}
Hello Nathan making a call as
[self dataReturn:#"Bill"];
to function
-(void)dataReturn:(NSString *)tableName{
sqlite3 *database;
sqlite3_stmt *statement;
NSString *queryString = [NSString stringWithFormat:#"SELECT SUM(price) AS TOTAL FROM %#", tableName];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
if(sqlite3_prepare_v2(database, [queryString UTF8String], -1, &statement, nil) == SQLITE_OK){
while (sqlite3_step(statement) == SQLITE_ROW) {
int field1 = sqlite3_column_int(statement, 0);
NSLog(#"The sum is %d ", field1);
}
}
}
}
will Fetch you desired data. The schema for Table "Bill" is "CREATE TABLE Bill (price double,quantity INTEGER)". The result fetched will have columns indexed from "0" so we pass 0 for first column. Hope you can take some hint from it. Cheers!!
int field1 = sqlite3_column_int(statement, 0);
From the sqlite3_column_int docs:
The leftmost column of the result set has the index 0.
Additionally, that function returns an int, not an int*. Try:
int field2 = sqlite3_column_int(statement, 0);
I am using what, according to my Xcode debugger, is proper syntax to delete a row from a table in my project. However, when I go back to check my database, it still exists. My other SQL syntax for inserting entries is correct, so I'm not sure what I'm doing wrong. NSLogs confirm both variables are being sent correctly:
-(void) deleteSelectedRowFromTable: (NSString *) tableName cityName:(NSString *)city
{
[self openDB];
NSString *sqlStr = [NSString stringWithFormat:#"DELETE FROM %# WHERE city LIKE %#", tableName, city];
const char *sql = [sqlStr UTF8String];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, sql, -1, &statement, nil) == SQLITE_OK) {
NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(db));
}
sqlite3_finalize(statement);
sqlite3_close(db);
}
Try this statement
NSString *sqlStr = [NSString stringWithFormat:#"DELETE FROM '%#' WHERE city LIKE '%#%%'", tableName, city];
Check that the operand to LIKE is a string (should have quotation marks around it). I've never used XCode, but if you change your 5th line to read:
NSString *sqlStr = [NSString stringWithFormat:#"DELETE FROM %# WHERE city LIKE '%#'", tableName, city];
Does that work?
you have just prepared the statement, you should step that statement.
-(void) deleteSelectedRowFromTable: (NSString *) tableName cityName:(NSString *)city
{
[self openDB];
NSString *sqlStr = [NSString stringWithFormat:#"DELETE FROM %# WHERE city LIKE %#", tableName, city];
const char *sql = [sqlStr UTF8String];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, sql, -1, &statement, nil) != SQLITE_OK)
{
/**this one will execute when there is error in your query**/
NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(db));
}
else
{
/************just add this one****************/
sqlite3_step(statement);
}
sqlite3_finalize(statement);
sqlite3_close(db);
}
i hope this one will help you.