Search code examples
c#winformssqlitesql-limit

Can I use a parameter for the LIMIT condition in sqlite query


Quick question on an SQLite query I'm working on for a C# application:

Can I use a parameter to set the "LIMIT" value in a query? For example I would like to do this:

SQLiteCommand cmd = new SQLiteCommand("SELECT FROM ... WHERE ... LIMIT @items");
cmd.Parameters.Add(new SQLiteParameter("items", numberofItems));

Is this a thing? Or is there an equivalent? I'd like to be able to set the LIMIT value programmatically if I can.

I tried googling this question for a while, but I didn't come up with anything so maybe y'all can help. Thanks a lot!


Solution

  • Yes, this works. Don't be afraid to just test something if you are not sure if it works. You didn't mention what problems you were having. Here is a working example

    SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder();
    builder.DataSource = "test.db";
    
    SQLiteConnection connection = new SQLiteConnection(builder.ConnectionString);
    using (connection.Open())
    {
        SQLiteCommand command = new SQLiteCommand("select * from people limit @limitNum", connection);
        command.Parameters.Add(new SQLiteParameter("limitNum", 2));
        SQLiteDataReader reader = command.ExecuteReader();
    
        while (reader.Read())
        {
            Console.WriteLine(reader.GetValue(0));
        }
    }