1

I am using sqlite database for store my data.But it is showing error of "database is locked" while insert query.Here is my code

 sqlite3_stmt    *statement;
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        const char *dbpath = [[defaults objectForKey:@"dbpath"] UTF8String];

        if (sqlite3_open(dbpath, &studentDB22) == SQLITE_OK)
        {
            NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO Emotion_videos (name) VALUES (\"%@\")",filePath];
            const char *query_stmt = [insertSQL UTF8String];
                if (sqlite3_prepare_v2(studentDB22, query_stmt, -1, &statement, NULL) == SQLITE_OK)
                {
                    NSLog(@"shi h2345");
                    if (sqlite3_step(statement) == SQLITE_ROW)
                    {
                        printf( "could not prepare statement: %s\n", sqlite3_errmsg(studentDB22));

                    }

                }
            sqlite3_finalize(statement);
        }
        else
        {
                   printf( "could not prepare statement: %s\n", sqlite3_errmsg(studentDB22));
        }

I am able to insert data for two or three times but when it runs again,it shows database locked error.

2 Answers 2

2

You open the database but you don't close it.

You shouldn't use string formats to create queries. You should put ? placeholders in the query then bind the proper value. This takes care of things like properly quoting and escaping string values.

NSString *insertSQL = @"INSERT INTO Emotion_videos (name) VALUES (?)";

After you prepare the statement, call sqlite3_bind_text to bind the string value.

Also. don't use sqlite3_open, use sqlite3_open_v2. It's better and gives you more control.

Sign up to request clarification or add additional context in comments.

3 Comments

what will be the parameter in sqlite3_open_v2??
My query is running only for two times.Third time query is not executing neither app being crash. Help pls.
Do you close the database each time you open it? Are you running the code in the debugger? What is different the third time?
0

You have missed one of the important step while creating a database connection:-

Close Database connection before creating connection if it is already made.

   if (sqlite3_open([[self dataFilePath] UTF8String], &database)
    != SQLITE_OK) { sqlite3_close(database); NSAssert(0, @"Failed to open database");
    }

Use at the end of the function:-

sqlite3_close(database);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.