0

So I'm currently compiling a simple SQL query like this:

    const char *sqlQuery = "SELECT value FROM settings WHERE name=? LIMIT 1";

    sqlite3_stmt *compiledStatement;

    if(sqlite3_prepare_v2(database, sqlQuery, -1, &compiledStatement, nil) == SQLITE_OK)
    {
        sqlite3_bind_text(compiledStatement, 1, [name UTF8String], -1, SQLITE_TRANSIENT);

        while(sqlite3_step(compiledStatement) == SQLITE_ROW)
        {
            NSString *theValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];

            // ...
        }
    }

However I would like to be able to change the table name I'm calling. I thought I could change the sqlQuery to:

const char *sqlQuery = "SELECT value FROM ? WHERE name=? LIMIT 1";

And then bind it before I bind the name value, however this doesn't work. I guess this is designed to only work for selection args...

Does anyone know if there is a way to insert the table name here or do I just have to do it in plain text?

2 Answers 2

1
NSString *queryString = [NSString stringWithFormat:@"SELECT value FROM %@ WHERE name=%@ LIMIT 1",tablename,attribute];

 const char *sqlQuery = [queryString UTF8String];

Hope this helps..

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

3 Comments

Why didn't that answer happen in my brain ;) Thanks for the help!
If the "name" parameter comes from user input, then you should still use sqlite3_bind_text for "name = ?", to avoid the danger of SQL injection (xkcd.com/327)
In my case the "name" parameter is a #define I have stored in the header file, but you make a valid point for anyone reading this who does use it for something based on user input.
1
 NSString *sqlTemplate = @"SELECT value FROM %@ WHERE name=? LIMIT 1";

 //assuming you have your table name stored in tableName variable
const char *sqlQuery = [[NSString stringWithFormat:sqlTemplate, tableName] UTF8String];

sqlite3_stmt *compiledStatement;

if(sqlite3_prepare_v2(database, sqlQuery, -1, &compiledStatement, nil) == SQLITE_OK)
{
    sqlite3_bind_text(compiledStatement, 1, [name UTF8String], -1, SQLITE_TRANSIENT);

    while(sqlite3_step(compiledStatement) == SQLITE_ROW)
    {
        NSString *theValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];

        // ...
    }
}

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.