1

通过向查询中添加参数,引发的错误就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;

UPDATE = 解决方案 正如@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); <<==
4

3 回答 3

3

您没有使用已添加参数的 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];
}
于 2018-07-08T08:56:24.033 回答
0

喜欢 :

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

后 :

   sqlCmd.Parameters.AddWithValue("$id", 1);
于 2018-07-08T08:56:30.283 回答
0

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

string CommandText = "select * from Words where id = @id"; 
于 2018-07-08T08:41:22.650 回答