[英]Inserting multiple parameter values to a sqlite table using c#
這是我要創建的方法的代碼:
public void writeIt(string inputText, bool fasting)
{
var dbConnect = new SQLiteConnection("Data Source=database.sqlite;Version=3;");
dbConnect.Open();
using (SQLiteTransaction insertTrans = dbConnect.BeginTransaction())
{
using (SQLiteCommand insertCommand = new SQLiteCommand(dbConnect))
{
SQLiteParameter resultEntry = new SQLiteParameter();
insertCommand.CommandText = "INSERT INTO result(testResult, fasting) VALUES(@param1, @param2)";
insertCommand.Parameters.Add(new SQLiteParameter("@param1", System.Data.SqlDbType.VarChar).Value = inputText);
if(fasting)
{
insertCommand.Parameters.Add(new SQLiteParameter("@param2", System.Data.SqlDbType.Int).Value = "1");
}
else
{
insertCommand.Parameters.Add(new SQLiteParameter("@param2", System.Data.SqlDbType.Int).Value = "0");
}
insertCommand.ExecuteNonQuery();
}
insertTrans.Commit();
}
我正在使用官方的sqlite數據庫引擎(如果有的話)。 目前,當我嘗試存儲數據時顯示的錯誤顯示以下內容
在行“ insertCommand.Parameters.Add(new SQLiteParameter(“ @ param1”,System.Data.SqlDbType.VarChar)”處,“無法將類型為'System.String'的對象轉換為類型為'System.Data.SQLite.SQLiteParameter'” .Value = inputText);“。
我公開(並且自由地)承認我不太確定如何解決此問題,因為我是新手,這是我的第二個有意義的項目。
感謝您提前的善意。
當調用傳遞DbParameter對象的DbParameterCollection (SQLiteParameterCollection背后的基類)的Add方法時 ,返回值是Integer,而不是剛剛添加到集合中的DbParameter。
因此,您不能使用返回值,因為它是DbParameter並嘗試設置Value屬性。
相反,您應該使用帶有參數名稱和類型的Add重載。 這將返回一個DbParameter對象,因此您可以編寫:
insertCommand.Parameters.Add("@param1", System.Data.SqlDbType.VarChar).Value = inputText;
if(fasting)
{
insertCommand.Parameters.Add("@param2", System.Data.SqlDbType.Int).Value = 1;
}
else
{
insertCommand.Parameters.Add("@param2", System.Data.SqlDbType.Int).Value = 0;
}
您正在創建整數類型參數,因此將其值設置為整數而不是字符串
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.