Содержание
- System data sqlite sqliteexception unknown error insufficient parameters supplied to the command
- Answered by:
- Question
- Как исправить « исключение SQLite, недостаточно параметров, предоставленных команде » при использовании оператора INSERT
- 1 ответ
- Как исправить « исключение SQLite, недостаточно параметров, предоставленных команде » при использовании оператора INSERT
- Unexpected error «Insufficient parameters supplied to the command» when updating to SQLite #475
- Comments
- Description
- Repro steps
- Expected behavior
- Actual behavior
- Known workarounds
- Related information
- System data sqlite sqliteexception unknown error insufficient parameters supplied to the command
- Answered by:
- Question
System data sqlite sqliteexception unknown error insufficient parameters supplied to the command
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I made a new thread for this.
I get this error while i trying a datatable in the database.
—————————
code = Unknown (-1), message = System.Data.SQLite.SQLiteException (0x80004005): unknown error
Insufficient parameters supplied to the command
bij System.Data.SQLite.SQLiteStatement.BindParameter(Int32 index, SQLiteParameter param)
bij System.Data.SQLite.SQLiteStatement.BindParameters()
bij System.Data.SQLite.SQLiteCommand.BuildNextCommand()
bij System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index)
bij System.Data.SQLite.SQLiteDataReader.NextResult()
bij System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
bij System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
bij System.Data.SQLite.SQLiteCommand.ExecuteNonQuery(CommandBehavior behavior)
bij System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()
bij Frya.Database.Database.XlxsNaarSqlite(DataTable dt) in D:UsersRinaldoDocumentsVisual Studio 2017ProjectsFryaFryaDatabaseDatabase.cs:regel 147
The code is as followed:
Hope that someone knows how to insert in to database
Источник
Как исправить « исключение SQLite, недостаточно параметров, предоставленных команде » при использовании оператора INSERT
Я пытаюсь вставить данные из объекта в свою таблицу базы данных sqlite. Я продолжаю получать ту же ошибку при попытке сделать это.
При вставке данных в другую таблицу (слова) той же базы данных, используя ту же технику, я могу успешно вставить данные без ошибок. Это заставляет меня думать, что мое значение SQLiteConnection ‘cnn’ не является проблемой. Я убедился, что имена свойств объекта такие же, как и имена полей в таблице. В этой конкретной таблице нет первичного ключа, но я не уверен, проблема в этом или нет.
Код, который не работает:
Код, который действительно работает:
Модель класса bridgeRecord выглядит так:
Это ошибка, которую я получаю:
Я ожидал, что объект bridgeRecord предоставит параметры для вставки, но это не так. Хотя объект «Word», кажется, предоставляет параметры очень хорошо, что меня очень смущает.
Любая помощь будет очень высоко ценится. Это мой первый вопрос о переполнении стека, извините, если ответ очевиден 🙂
1 ответ
Следуя совету Паскаля в комментариях, я использовал метод command.parameters.add, чтобы исправить свою проблему. Я подготовил статус заранее, а затем добавил параметры в их правильные места. Окончательный код теперь выглядит так:
Было бы лучше найти исправление, которое позволило бы коду работать как другой оператор INSERT, но этого будет достаточно.
Источник
Как исправить « исключение SQLite, недостаточно параметров, предоставленных команде » при использовании оператора INSERT
Я пытаюсь вставить данные из объекта в свою таблицу базы данных sqlite. Я продолжаю получать ту же ошибку при попытке сделать это.
При вставке данных в другую таблицу (слова) той же базы данных, используя ту же технику, я могу успешно вставить данные без ошибок. Это заставляет меня думать, что мое значение SQLiteConnection ‘cnn’ не является проблемой. Я убедился, что имена свойств объекта такие же, как и имена полей в таблице. В этой конкретной таблице нет первичного ключа, но я не уверен, проблема в этом или нет.
Код, который не работает:
Код, который действительно работает:
Модель класса bridgeRecord выглядит так:
Это ошибка, которую я получаю:
Я ожидал, что объект bridgeRecord предоставит параметры для вставки, но это не так. Хотя объект «Word», кажется, предоставляет параметры очень хорошо, что меня очень смущает.
Любая помощь будет очень высоко ценится. Это мой первый вопрос о переполнении стека, извините, если ответ очевиден 🙂
привет, можешь ли ты распечатать какие-нибудь данные (bridgeRecord). Может ли быть в ваших данных нулевое значение? С другой стороны, вы можете попробовать использовать command.Parameters.Add (new SqliteParameter («@ Name», «Has»));
Привет, при отладке я вижу, что bridgeRecord не имеет нулевых значений до выполнения оператора SQL. И да, я рассматривал возможность использования метода command.Parameters.add, но делать это для каждого параметра кажется немного громоздким. Тем не менее, это может быть единственное решение, спасибо за рекомендацию.
спасибо за ваш возврат, да, это может быть первый способ увидеть, что именно вызывает ошибку, это может быть возможное отсутствие преобразования типа данных или другая причина. Извините, но у меня нет необходимой конфигурации для воспроизведения на моем компьютере.
Источник
Unexpected error «Insufficient parameters supplied to the command» when updating to SQLite #475
Description
Whe I run the following code
Repro steps
Steps to reproduce the problem
- Step A
Create a table like the following
Step B
Insert the selected record so that it finds it
Step C
Run the above F# code
Expected behavior
The record should be updated without error
Actual behavior
I’m getting the following error
Known workarounds
No one at the moment.
- Used database SQLite Version 3
- Operating system Windows 7
- Branch latest version of nuget SQLProvider (from PM of VisualStudio2015) v1.1.18
- .NET Runtime: 4.6.1
The text was updated successfully, but these errors were encountered:
As far as I understand, the whole key is expected even if it is not needed (since the exactlyOneOrDefault is working in the query)
Yes. I would recommend considering creating a separate Id-field to the database table,
Need of the exact table key is actually just to protect developers.
Because otherwise the user could end-up in a situation where
the generated update clause would cause «1100 row(s) affected»
even if the developer thought that this should hit only one item.
I cannot really create a separate id-field to the sqlite table since it is already used in another app and it makes sense to have a multiple-fields key. but I actually can complete the key with the other (somehow fixed) fields in the query, so. yes, the issue is solved. Thanks
Yes I understand the protection even tough the exactlyOneOrDefault already guaranteed it. Anyway, fair enough, ok.
. which leads to the next question that how do you expect exactly one when you don’t use your primary key items in your where-clause. Anyways, that’s none of my business. 🙂
Yes, you’re right, that’s a very good question. The full code needs a complex join with other tables. I was trying to do an intermediate test of a drafted version. Anyway, should you look at the complete requirement and the full join (which I am striving to write now) it wouldn’t be obvious that there is a unique value either 🙂 Just imagine there is a table with consecutive ranges and that one has to find the range which a certain value belongs to
Indeed the join
gives me an error
What does it mean exactly? Thanks again
We don’t currently support joining to static fields like «TEST» and «MR», so please use a where-filter for those.
Thank you very much for your support
Why can’t I test if a tuple is null?
the above code doesn’t compile because
but it can be null (therefore crashing) at runtime. Am I supposed to box it or is it the same bug as for a single entity?
Do you have SQLProvider 1.1.18 where this is fixed?
One thing to consider is using UseOptionTypes in the static constructor parameters of your SQLDataProvider.
Yes, I have 1.1.18 and I’ve aslo set UseOptionTypes now.
Hmm, in that case it should return Option and you should be able to
Now I actually found a problem that exactlyOneOrDefault doesn’t limit the selected SQL items to 2 as it should.
How about headOrDefault ?
Edit: more complete example
Edit 2: Maybe limit 2 is not important as hitting the limit should never happen.
I’ve tried also headOrDefault now but I can’t match Some/None like you do above
I cannot manage to create an unit test that would fail with exactlyOneOrDefault.
Seems to work perfectly.
Do you have a select (p,a) after a join? And then you can do if not (isNull foundWSTuple) then ?
My code above does compile only when I box the tuple. screenshot here
No I don’t use isNull. If you have UseOptionTypes then you should be able to say
e.g. if foundWSTuple.IsSome then . Could your problem be related to VS2015 caching. 🙂
closed solution and VS2015, reopened and rebuild as per your suggestion but still
error FS0039: The field, constructor or member ‘IsSome’ is not defined
Can you clone this repository and open SQLProvider.Tests.sln . It has a file QueryTests.fs which is using SQLite as database, and has a lot of tests. Can you try to write a test with exactlyOneOrDefault which would fail, and send either a PR or just copy&paste the test here?
I’ve not yet cloned but the idea is to build a test like the following
to check if isNull(qry) does compile
I didn’t have any problems with select (cust.CustomerId,cust.CustomerId) in a query.
Yes, it produced null at runtime, as it should.
I didn’t use isNull as it’s not an operator of SQLProvider, it comes from FSharp core operators, and it’s implementation is depending the version of F# you use, which can vary. But you can use e.g. x <> null . Or as a work-around isNull(box(x)) should also work.
So from SQLProvider’s side:
- If exactlyOneOrDefault with not-found-items and UseOptionTypes=false (default) it should result a null.
- If exactlyOneOrDefault with not-found-items and UseOptionTypes=true it should result a None.
The problem with your later code is that qry result type is a tuple, which is a struct, not a class, and for a struct, you cannot have null as a default value. So there is no «default value», I don’t know what exactlyOneOrDefault should be then. But again I think this is a problem of F# language (query syntax) and not SQLProvider. 🙂
Edit: I opened dotnet/fsharp#3845 let’s see what they say.
Ok thank you very much for helping me! Much appreciated. I’m forced to materialize the second table in an array in-memory and I reduce the join to a single select to preceed in the meantime. Thanks again, let me know.
Источник
System data sqlite sqliteexception unknown error insufficient parameters supplied to the command
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I made a new thread for this.
I get this error while i trying a datatable in the database.
—————————
code = Unknown (-1), message = System.Data.SQLite.SQLiteException (0x80004005): unknown error
Insufficient parameters supplied to the command
bij System.Data.SQLite.SQLiteStatement.BindParameter(Int32 index, SQLiteParameter param)
bij System.Data.SQLite.SQLiteStatement.BindParameters()
bij System.Data.SQLite.SQLiteCommand.BuildNextCommand()
bij System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index)
bij System.Data.SQLite.SQLiteDataReader.NextResult()
bij System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
bij System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
bij System.Data.SQLite.SQLiteCommand.ExecuteNonQuery(CommandBehavior behavior)
bij System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()
bij Frya.Database.Database.XlxsNaarSqlite(DataTable dt) in D:UsersRinaldoDocumentsVisual Studio 2017ProjectsFryaFryaDatabaseDatabase.cs:regel 147
The code is as followed:
Hope that someone knows how to insert in to database
Источник
I made a new thread for this.
Hi folks
I get this error while i trying a datatable in the database.
—————————
—————————
code = Unknown (-1), message = System.Data.SQLite.SQLiteException (0x80004005): unknown error
Insufficient parameters supplied to the command
bij System.Data.SQLite.SQLiteStatement.BindParameter(Int32 index, SQLiteParameter param)
bij System.Data.SQLite.SQLiteStatement.BindParameters()
bij System.Data.SQLite.SQLiteCommand.BuildNextCommand()
bij System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index)
bij System.Data.SQLite.SQLiteDataReader.NextResult()
bij System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
bij System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
bij System.Data.SQLite.SQLiteCommand.ExecuteNonQuery(CommandBehavior behavior)
bij System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()
bij Frya.Database.Database.XlxsNaarSqlite(DataTable dt) in D:UsersRinaldoDocumentsVisual Studio 2017ProjectsFryaFryaDatabaseDatabase.cs:regel 147
The code is as followed:
public bool XlxsNaarSqlite(DataTable dt) { int count = 0; try { using (SQLiteTransaction transaction = con.BeginTransaction()) { foreach (DataRow row in dt.Rows) { using (SQLiteCommand insertSQL = new SQLiteCommand( "insert into Persoon(voornaam ,achternaam,straat,postcode, telMobiel," + " ris," + " emailadres, bank, project,isMedewerker, isLeider, telmobiel, geboortedatum)" + " values ( @voor, @achter, @straat, @Post, @mobiel, @Ris" + ", @email, @bank, @Project, @medewerker, @Leider, @telefoon, @geboorte)", con)) { insertSQL.Parameters.Add(new SQLiteParameter("@voor", SqlDbType.Text)); insertSQL.Parameters.Add(new SQLiteParameter("@achter", SqlDbType.Text)); //insertSQL.Parameters.Add(new SQLiteParameter("@Datum", SqlDbType.Date)); //insertSQL.Parameters.Add(new SQLiteParameter("@straat", SqlDbType.Text)); /* insertSQL.Parameters.Add(new SQLiteParameter("@post", SqlDbType.Text)); insertSQL.Parameters.Add(new SQLiteParameter("@huis", SqlDbType.Text)); insertSQL.Parameters.Add(new SQLiteParameter("@mobiel", SqlDbType.Text)); insertSQL.Parameters.Add(new SQLiteParameter("@email", SqlDbType.Text)); insertSQL.Parameters.Add(new SQLiteParameter("@RIS", SqlDbType.Text)); insertSQL.Parameters.Add(new SQLiteParameter("@Bank", SqlDbType.Text)); insertSQL.Parameters.Add(new SQLiteParameter("@project", SqlDbType.Text)); insertSQL.Parameters.Add(new SQLiteParameter("@medewerker", SqlDbType.Bit)); insertSQL.Parameters.Add(new SQLiteParameter("@Leider", SqlDbType.Bit)); insertSQL.Parameters.Add(new SQLiteParameter("@telefoon", SqlDbType.Text)); insertSQL.Parameters.Add(new SQLiteParameter("@geboorte", SqlDbType.Date)); */ insertSQL.ExecuteNonQuery(); count++; } } transaction.Commit(); //new General().WriteApplicationLog("Data successfully imported."); return true; } } catch (Exception ex) { FlexibleMessageBox.Show(ex.ToString() + "nTeller = " + count); return false; } finally { if (con.State == ConnectionState.Open) con.Close(); //dt = result; }
Hope that someone knows how to insert in to database
Greetings from Amsterdam the Netherlands
mixon-21 5 / 5 / 3 Регистрация: 05.03.2013 Сообщений: 220 |
||||
1 |
||||
29.07.2014, 00:23. Показов 3212. Ответов 5 Метки нет (Все метки)
Помогите разобраться пожалуста.
выдает ошибку Необработанное исключение типа «System.Data.SQLite.SQLiteException» в System.Data.SQLite.dll Дополнительные сведения: unknown error Insufficient parameters supplied to the command какие параметры я недописал???
__________________
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
29.07.2014, 00:23 |
5 |
Заблокирован |
|
29.07.2014, 00:25 |
2 |
На какой строке выдает?
0 |
1448 / 1120 / 345 Регистрация: 11.04.2011 Сообщений: 2,615 |
|
29.07.2014, 07:12 |
3 |
какие параметры я недописал??? Если вас интересует конкретно этот вопрос, то ошибка возникает из-за параметра #id, который вы в комманду не передаете.
0 |
5 / 5 / 3 Регистрация: 05.03.2013 Сообщений: 220 |
|
30.07.2014, 23:51 [ТС] |
4 |
На какой строке выдает? выдает на этой строке.
SQLiteDataReader dr = cmd.ExecuteReader (); подскажите пожалуйста как добавить данные в таблицу???
0 |
36 / 25 / 12 Регистрация: 08.04.2013 Сообщений: 269 |
|
04.08.2014, 13:41 |
5 |
сначала dr.Read(), а потом проверка на наличие строк.
0 |
7 / 7 / 3 Регистрация: 16.03.2013 Сообщений: 18 |
|
05.08.2014, 22:22 |
6 |
У вас модифицирующий запрос (вставка строки), что вы собрались читать Reader-ом?
0 |
OK, with everyone’s guidance I seem to have worked most things out now. I still have one issue that evades me.
Here is my cleaned up code that seems to work great so far, with the one exception:
using System; using System.Data; using System.Data.SQLite; using System.Windows.Forms; namespace ArukahHouse { public partial class MileageTrack : Form { SQLiteConnection sqlite_conn; SQLiteCommand sqlite_cmd; SQLiteDataReader sqlite_datareader; string query; SQLiteDataAdapter adapter; BindingSource bsource = new BindingSource(); DataSet ds = null; public MileageTrack() { InitializeComponent(); } private void MileageTrack_Load(object sender, EventArgs e) { sqlite_conn = new SQLiteConnection("Data Source=Arukah.db;Foreign Keys=True;"); query = "SELECT car_ID, car_Make, car_Model, car_Year FROM Car"; sqlite_cmd = new SQLiteCommand(query,sqlite_conn); sqlite_conn.Open(); sqlite_cmd.Connection = sqlite_conn; sqlite_datareader = sqlite_cmd.ExecuteReader(); while (sqlite_datareader.Read()) { query = sqlite_datareader[0].ToString(); autoidcomboBx.Items.Add(query); } sqlite_datareader.Close(); } private void autoidcomboBx_SelectedIndexChanged(object sender, EventArgs e) { LoadData(); } private void LoadData() { if (autoidcomboBx.SelectedIndex >= 0) { sqlite_conn = new SQLiteConnection("Data Source=Arukah.db;Foreign Keys=True;"); query = "SELECT STRFTIME(mile_Date) AS MileDate, begin_Miles, end_Miles FROM Mileage WHERE car_ID="+ autoidcomboBx.SelectedItem; adapter = new SQLiteDataAdapter(query, sqlite_conn); sqlite_conn.Open(); ds = new DataSet(); SQLiteCommandBuilder builder = new SQLiteCommandBuilder(adapter); adapter.Fill(ds, "Mileage"); bsource.DataSource = ds.Tables["Mileage"]; dataGridView1.DataSource = bsource; sqlite_conn.Close(); } } } }
The problem lies in the datareader strings being passed to the combobox. If I only use
query = sqlite_datareader[0].ToString();
everything works excellent. The value passed to the combobox is the car_ID which is either:
1
2
3
If I use the following, I get an exception error and it highlights the value of the string index [1].
query = sqlite_datareader[0].ToString()+" "+ sqlite_datareader[1].ToString()+" "+ sqlite_datareader[2].ToString() + " " + sqlite_datareader[3].ToString();
System.Data.SQLite.SQLiteException: 'SQL logic error<br /> near "CHEVROLET": syntax error'
Which is the value of sqlite_datareader[1].ToString that I select in the combobox. The combobox loads fine with these values:
1 FORD F-150 2018
2 DODGE RAM 2021
3 CHEVROLET EQUINOX 2017
the error occurs on selection LoadData().
Any thoughts? Many thanks!
Я пытаюсь вставить данные из объекта в таблицу базы данных 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», кажется, обеспечивает параметры очень хорошо, что меня очень смущает.
Любая помощь будет очень высоко ценится. Это мой первый вопрос о переполнении стека, поэтому извините, если ответ предельно очевиден
Description
Whe I run the following code
let foundWS = query { for m in platts do where (m.AreaFrom = Some spotPrice.Code && m.RefDate = Some spotPrice.Date) exactlyOneOrDefault } if not (isNull foundWS) then foundWS.WsValue <- Some spotPrice.Price // <= it runs this code as expected foundWS.AreaTo <- Some "Test ..." else let newWS = platts.Create() newWS.AreaFrom <- Some spotPrice.Code newWS.RefDate <- Some spotPrice.Date.Date newWS.WsValue <- Some spotPrice.Price newWS.AreaTo <- Some "Test ..." appCtx.SubmitUpdates() // <-- exception
Repro steps
Steps to reproduce the problem
- Step A
Create a table like the following
CREATE TABLE [test_table] ( [ref_date] DATE NULL, [provider] VARCHAR(20) NULL, [type] VARCHAR(20) NULL, [area_from] VARCHAR(20) NULL, [area_to] VARCHAR(20) NULL, [size_key] VARCHAR(20) NULL, [WsValue] FLOAT NULL, [ignore] BOOLEAN NULL, PRIMARY KEY ([ref_date],[provider],[type],[area_from],[area_to],[size_key]) )
-
Step B
Insert the selected record so that it finds it -
Step C
Run the above F# code
Expected behavior
The record should be updated without error
Actual behavior
I’m getting the following error
Insufficient parameters supplied to the command in System.Data.SQLite.SQLiteStatement.BindParameter(Int32 index, SQLiteParame ter param) in System.Data.SQLite.SQLiteStatement.BindParameters() in System.Data.SQLite.SQLiteCommand.BuildNextCommand() in System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index) in System.Data.SQLite.SQLiteDataReader.NextResult() in System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavi or behave) in System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior) in System.Data.SQLite.SQLiteCommand.ExecuteNonQuery(CommandBehavior behavior) in System.Data.SQLite.SQLiteCommand.ExecuteNonQuery() in <StartupCode$FSharp-Data-SqlProvider>.$Providers.SQLite.FSharp-Data-Sql-Co mmon-ISqlProvider-ProcessUpdates@794-7.Invoke(SqlEntity e) in Microsoft.FSharp.Collections.SeqModule.Iterate[T](FSharpFunc`2 action, IEn umerable`1 source) in FSharp.Data.Sql.Providers.SQLiteProvider.FSharp-Data-Sql-Common-ISqlProvid er-ProcessUpdates(IDbConnection con, ConcurrentDictionary`2 entities, Transactio nOptions transactionOptions, FSharpOption`1 timeout) in <StartupCode$FSharp-Data-SqlProvider>.$SqlRuntime.DataContext.f@1-56(SqlDa taContext __, IDbConnection con, Unit unitVar0) in FSharp.Data.Sql.Runtime.SqlDataContext.FSharp-Data-Sql-Common-ISqlDataCont ext-SubmitPendingChanges()
Known workarounds
No one at the moment.
Related information
- Used database SQLite Version 3
- Operating system Windows 7
- Branch latest version of nuget SQLProvider (from PM of VisualStudio2015) v1.1.18
- .NET Runtime: 4.6.1
I have the following code:
try
{
//Create connection
SQLiteConnection conn = DBConnection.OpenDB();
//Verify user input, normally you give dbType a size, but Text is an exception
var uNavnParam = new SQLiteParameter("@uNavnParam", SqlDbType.Text) { Value = uNavn };
var bNavnParam = new SQLiteParameter("@bNavnParam", SqlDbType.Text) { Value = bNavn };
var passwdParam = new SQLiteParameter("@passwdParam", SqlDbType.Text) {Value = passwd};
var pc_idParam = new SQLiteParameter("@pc_idParam", SqlDbType.TinyInt) { Value = pc_id };
var noterParam = new SQLiteParameter("@noterParam", SqlDbType.Text) { Value = noter };
var licens_idParam = new SQLiteParameter("@licens_idParam", SqlDbType.TinyInt) { Value = licens_id };
var insertSQL = new SQLiteCommand("INSERT INTO Brugere (navn, brugernavn, password, pc_id, noter, licens_id)" +
"VALUES ('@uNameParam', '@bNavnParam', '@passwdParam', '@pc_idParam', '@noterParam', '@licens_idParam')", conn);
insertSQL.Parameters.Add(uNavnParam); //replace paramenter with verified userinput
insertSQL.Parameters.Add(bNavnParam);
insertSQL.Parameters.Add(passwdParam);
insertSQL.Parameters.Add(pc_idParam);
insertSQL.Parameters.Add(noterParam);
insertSQL.Parameters.Add(licens_idParam);
insertSQL.ExecuteNonQuery(); //Execute query
//Close connection
DBConnection.CloseDB(conn);
//Let the user know that it was changed succesfully
this.Text = "Succes! Changed!";
}
catch(SQLiteException e)
{
//Catch error
MessageBox.Show(e.ToString(), "ALARM");
}
It executes perfectly, but when I view my «brugere» table, it has inserted the values: ‘@uNameParam’, ‘@bNavnParam’, ‘@passwdParam’, ‘@pc_idParam’, ‘@noterParam’, ‘@licens_idParam’ literally. Instead of replacing them.
I have tried making a breakpoint and checked the parameters, they do have the correct assigned values. So that is not the issue either.
I have been tinkering with this a lot now, with no luck, can anyone help?
Oh and for reference, here is the OpenDB method from the DBConnection class:
public static SQLiteConnection OpenDB()
{
try
{
//Gets connectionstring from app.config
const string myConnectString = "data source=data;";
var conn = new SQLiteConnection(myConnectString);
conn.Open();
return conn;
}
catch (SQLiteException e)
{
MessageBox.Show(e.ToString(), "ALARM");
return null;
}
}
Forum Rules |
|