Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to parameterize table and column names in SQLite queries?

Tags:

c#

sqlite

Im trying to perform a parameterized query in SQLite from C#, and the method im using is along the lines of creating a static command with

        SQLiteCommand cmd = new SQLiteCommand(
        "SELECT [ID]" +
            ",[email]" +
            ",[serializedata]" +
            ",[restrictions]" +
        " FROM " + UserTable +
        " WHERE @search = @searchparam", SQLConnection);

        cmd.Parameters.Add(new SQLiteParameter("@searchparam"));
        cmd.Parameters.Add(new SQLiteParameter("@search"));

and calling it like this:

        Command.Parameters["@searchparam"].Value = searchdata;
        Command.Parameters["@search"].Value = search;
        SQLiteDataAdapter slda = new SQLiteDataAdapter(UserSelectUsernameCommand);
        DataSet ds = new DataSet();
        slda.Fill(ds);
        User[] array = new User[ds.Tables[0].Rows.Count];
        int index = 0;
        foreach (DataRow row in ds.Tables[0].Rows)
        {
            array[index] = new User(this, row);
            index++;
        }
        return array;

but im getting an error along the line of " '@search' is not a correct column name " or something like that. if i use a constant column name, and only use the data for parameters it works, but i dont want to create 10 different commands for when i need to search by different column names.

What is the issue here?

like image 955
caesay Avatar asked Nov 10 '10 05:11

caesay


People also ask

Does SQLite support parameterized query?

SQLite doesn't support output parameters. Return values in the query results instead.

How do I see column names in SQLite?

Click on Columns and drag it to the query window. This will enumerate the columns names in that given table separated by comma at the cursor position. (easier/faster than writing queries for an equivalent result!). sqlite> .

Are SQLite column names case sensitive?

SQLite Case SensitivitySQLite is a case insensitive. Table names and column names can be typed in uppercase, lowercase, or mixed case, and different capitalizations of the same database object name can be used interchangeably.


1 Answers

Generally things like column names (or table names) can not be parameterised - and the fact that there are different indices means that it will have to be a different plan internally. So you will have to use concatenation - but be careful to white-list the known column names to prevent sql injection:

    SQLiteCommand cmd = new SQLiteCommand(@"
    SELECT [ID],[email],[serializedata],[restrictions]
    FROM " + whiteListedUserTable + @"
    WHERE [" + whiteListedColumnName + @"] = @searchparam", SQLConnection);

    cmd.Parameters.Add(new SQLiteParameter("@searchparam"));
    ...
    Command.Parameters["@searchparam"].Value = searchdata;
like image 143
Marc Gravell Avatar answered Sep 22 '22 22:09

Marc Gravell