C#将字符串传递给Sqlite参数

时间:2018-10-25 20:12:21

标签: c# sqlite

我正在尝试将字符串(函数的输出)传递给SqLite查询,并用它来更新数据库。我收到一个错误消息,告诉我字符串不是有效的数据类型。

  IList<string> classList = new List<string>(){ "Saber", "Archer", "Lancer", "Rider",
     "Caster", "Assassin", "Berserker", "Ruler", "Avenger", "Moon Cancer"};
    public string setClass(int uid)
    {
        string newClass;
        int remainder = uid % 10;
        newClass = classList[remainder];
        return(newClass);
    }
    [NadekoCommand, Usage, Description, Aliases]
    public async Task initialiseClasses()
    {
        using (SqliteConnection _db = new SqliteConnection(@"Filename=.\myDb.db"))
        {
            _db.Open();
            string newSQL = "ALTER TABLE DiscordUser ADD Class char";
            SqliteCommand command = new SqliteCommand(newSQL, _db);
            command.ExecuteReader();
            string tempClass = setClass(7);  //temporary input
            newSQL = "UPDATE DiscordUser SET Class = @newClass";
            command.Parameters.Add(new SqliteParameter("@newClass", SqliteType.Text).Value = tempClass);
            command = new SqliteCommand(newSQL, _db);
            command.ExecuteReader();
        }
    }

我正在尝试将tempClass传递到Sqlite查询中。

1 个答案:

答案 0 :(得分:0)

  1. 您正在创建新命令, 是在将参数分配给命令后导致没有执行参数的命令。
  2. 可以重写参数集合上的Add,使它更流畅,请参见下面的更改。
  3. ExecuteReader应该是ExecuteNonQuery

如果使用using块构造代码,则更容易查看命令实例的范围。见下文:

public async Task initialiseClasses()
{
    using (SqliteConnection _db = new SqliteConnection(@"Filename=.\myDb.db"))
    {
        _db.Open();
        string newSQL = "ALTER TABLE DiscordUser ADD Class char";
        using(SqliteCommand command = new SqliteCommand(newSQL, _db))
        {
            command.ExecuteNonQuery();
        }

        string tempClass = setClass(7);  //temporary input
        newSQL = "UPDATE DiscordUser SET Class = @newClass";
        using(SqliteCommand command = new SqliteCommand(newSQL, _db))
        {
            command.Parameters.Add("@newClass", SqliteType.Text).Value = tempClass;
            command.ExecuteNonQuery();
        }
    }
}