簡體   English   中英

C#將字符串傳遞給Sqlite參數

[英]C# passing a string to an Sqlite parameter

我正在嘗試將字符串(函數的輸出)傳遞給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. 將參數分配給命令后,您正在創建一個新命令這導致沒有執行參數的命令。
  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();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM