SQLite 提供给命令的参数不足

SQLite Insufficient parameters supplied to the command

通过向查询添加参数,在 DB.Fill(DS) 行上引发了错误。 参数@id 正好等于查询的参数。 我搜索了很多,但所有解决方案都是关于参数名称的拼写错误。

SQLiteDataAdapter DB;      
DataSet DS = new DataSet();
DataTable DT = new DataTable();

SetConnection();
sqlCmd = sqlCon.CreateCommand();
string CommandText = "select * from Words where id = @id"; //query;
await sqlCon.OpenAsync();

sqlCmd.Parameters.AddWithValue("@id", 1);
DB = new SQLiteDataAdapter(CommandText, sqlCon);

DS.Reset();
await Task.Run(() => { DB.Fill(DS); });
DT = DS.Tables[0];
sqlCon.Close();
return DT;

更新=解决方案 正如@steve16351 所说,问题出在 CommandText 上。 只需将查询添加到 sqlCmd 并将其作为 SQLiteDataAdapter 参数发送。

sqlCmd = sqlCon.CreateCommand();
sqlCmd.CommandText("select * from Words where id = @id"); //query; <<==  
await sqlCon.OpenAsync();
sqlCmd.Parameters.AddWithValue("@id", 1);
DB = new SQLiteDataAdapter(sqlCmd); <<==

赞用于文本比较。您只需要匹配或不匹配,因此:

string CommandText = "select * from Words where id = @id"; 

您没有使用添加了参数的 SQL 命令,而是直接传递了 SQLiteDataAdapter 命令文本。使用带命令对象的重载:

sqlCmd.CommandText = "select * from Words where id = @id"; //query;
sqlCmd.Parameters.AddWithValue("@id", 1);
DB = new SQLiteDataAdapter(sqlCmd);

这是一个更完整的例子:

using (var conn = new SQLiteConnection(@"Data Source=c:\temp\mydbthatdoesnotexistyet.db;Version=3;"))
{
    conn.Open();

    // create the words table
    var create = conn.CreateCommand();
    create.CommandText = "CREATE TABLE Words (Id INT, Word TEXT)";
    create.ExecuteNonQuery();

    // insert data to the table
    var populate = conn.CreateCommand();
    populate.CommandText = "INSERT INTO Words (Id, Word) VALUES (@Id, @Word)";
    populate.Parameters.AddWithValue("@Id", 1);
    populate.Parameters.AddWithValue("@Word", "abc");
    populate.ExecuteNonQuery();

    // select the data back from the table
    var select = conn.CreateCommand();
    select.CommandText = "SELECT Word FROM Words WHERE Id = @Id";
    select.Parameters.AddWithValue("@Id", 1);

    SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(select);
    DataSet data = new DataSet();
    dataAdapter.Fill(data);
    DataTable table = data.Tables[0];
}

喜欢:

   string CommandText = "select * from Words where id = $id"; //query;

之后:

   sqlCmd.Parameters.AddWithValue("$id", 1);