Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# SQlite SQL logic error or missing database\r\nnear \"a\": syntax error

Tags:

c#

sqlite

I get an error when I try to run this method:

public bool InsertLog(string logMsg, string type)
{
    bool result = false;

    string sql = "INSERT INTO `log`(`logmsg`, `type`) VALUES (?a, ?b)";


    using (SQLiteConnection conn = new SQLiteConnection(m_dbConnectionString))
    {
        conn.Open();
        using (var comm = conn.CreateCommand())
        {
            comm.CommandText = sql;
            comm.Parameters.AddWithValue("?a", logMsg);
            comm.Parameters.AddWithValue("?b", type);
            int res = comm.ExecuteNonQuery();
            result = (res == 1);

        }
        conn.Close();
    }
    return result;
}

On this database table:

CREATE TABLE log (
    id        INTEGER  PRIMARY KEY,
    createdAt DATETIME DEFAULT (datetime('now', 'localtime') ),
    logmsg    TEXT,
    type      VARCHAR
);

The error message is {"SQL logic error or missing database\r\nnear \"a\": syntax error"} (System.Data.SQLite.SQLiteExpcetion). Where is the syntax error in the insert query? I don't see it. Can't I use prepared statements this way?

like image 550
szab.kel Avatar asked Feb 06 '26 11:02

szab.kel


1 Answers

Quotation marks in values (?, ?) are for positional parameters, so ?a is incorrect (you can, however, use something like ?123). If you want to use named parameters, change that to @a.

See Binding Values To Prepared Statements.

like image 86
Anton Gogolev Avatar answered Feb 09 '26 02:02

Anton Gogolev