我正在尝试将数据从一个对象插入到我的sqlite数据库表中。当我尝试这样做时,我一直收到相同的错误。
当使用相同的技术将数据插入到同一数据库的不同表(字)中时,我能够成功地插入数据而不会出错。这让我相信我的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”对象似乎提供了很好的参数,但这让我非常困惑。
任何帮助都将不胜感激。这是我的第一个堆栈溢出问题,所以如果答案非常明显,我很抱歉:)
发布于 2019-01-22 21:22:24
我采纳了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语句一样工作,但这个变通方法就足够了。
https://stackoverflow.com/questions/53988351
复制相似问题