如何修复使用INSERT语句时出现的“SQLite异常,提供给命令的参数不足”

y1aodyip  于 2023-01-21  发布在  SQLite
关注(0)|答案(2)|浏览(224)

我试图从一个对象中插入数据到我的sqlite数据库表中。我在尝试这样做的时候总是收到相同的错误。
将数据插入不同的表时(words),使用相同的技术,我能够成功地插入数据,没有错误。这使我相信我的SQLiteConnection值“cnn”不是问题所在。我已经确保对象属性的名称相同,表中的字段也相同。在这个特定的表中没有主键,但我不确定这是不是个问题。
不起作用的代码:

using (IDbConnection cnn = new SQLiteConnection(connection))
{
     foreach (bridgeRecord br in bridgeWords)
            {
                try
                {
                    cnn.Execute("insert into bridge (engWord, spaWord, frequency, wordClass) values (@engWord, @spaWord, @frequency, @wordClass)", br);
                }
                catch (SQLiteException ex)
                {
                    Console.WriteLine(ex);
                }
            }
}

有效的代码:

using (IDbConnection cnn = new SQLiteConnection(connection))
{
            foreach (Word w in words)
            {
                try
                {
                    cnn.Execute("insert into words (word, wordSimplified, confidence, difficulty, wordClass, wordCategory, dateTestedLast, popularity, language) " +
                    "values (@word, @wordSimplified, @confidence, @difficulty, @wordClass, @wordCategory, @dateTestedLast, @popularity, @language)", w);
                }
                catch (SQLiteException ex)
                {
                    wordsBouncedBack.Add(w.word);
                    continue;
                }
            }
}

“bridgeRecord”类模型如下所示:

class bridgeRecord
{
    public string engWord;
    public string spaWord;
    public int frequency;
    public string wordClass;
}

这是我收到的错误:

code = Unknown (-1), message = System.Data.SQLite.SQLiteException (0x80004005): unknown error
Insufficient parameters supplied to the command
at System.Data.SQLite.SQLiteStatement.BindParameter(Int32 index, SQLiteParameter param)

我期望"bridgeRecord“对象提供要插入的参数,但事实并非如此。虽然”Word“对象似乎很好地提供了参数,这让我很困惑。
任何帮助都将不胜感激。这是我的第一个堆栈溢出问题,所以我很抱歉,如果答案是非常明显的:)

cbeh67ev

cbeh67ev1#

我采纳了Pascal在注解中给出的建议,使用了command.parameters.add方法来解决我的问题。我事先准备了语句,然后将参数添加到正确的位置。最终代码如下所示:

SQLiteCommand command = new SQLiteCommand("insert into bridge (id, engWord, spaWord, frequency, wordClass) values (@id, @engWord, @spaWord, @frequency, @wordClass)",cnn);

                    command.Parameters.AddWithValue("@id", br.engWord + br.spaWord + br.frequency + br.wordClass);
                    command.Parameters.AddWithValue("@engWord", br.engWord);
                    command.Parameters.AddWithValue("@spaWord", br.spaWord);
                    command.Parameters.AddWithValue("@frequency", br.frequency);
                    command.Parameters.AddWithValue("@wordClass", br.wordClass);

                    command.ExecuteNonQuery();

最好找到一个修复方法,使代码能够像其他INSERT语句一样工作,但这种方法已经足够了。

zynd9foi

zynd9foi2#

有时候,当某个值包含单引号时,您可能会遇到此错误:

St. John's

相关问题