System data sqlite sqliteexception unknown error insufficient parameters supplied to the command

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 […]

Содержание

  1. System data sqlite sqliteexception unknown error insufficient parameters supplied to the command
  2. Answered by:
  3. Question
  4. Как исправить « исключение SQLite, недостаточно параметров, предоставленных команде » при использовании оператора INSERT
  5. 1 ответ
  6. Как исправить « исключение SQLite, недостаточно параметров, предоставленных команде » при использовании оператора INSERT
  7. Unexpected error «Insufficient parameters supplied to the command» when updating to SQLite #475
  8. Comments
  9. Description
  10. Repro steps
  11. Expected behavior
  12. Actual behavior
  13. Known workarounds
  14. Related information
  15. System data sqlite sqliteexception unknown error insufficient parameters supplied to the command
  16. Answered by:
  17. 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

  1. 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

Метки нет (Все метки)


Помогите разобраться пожалуста.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
namespace ExsecuteRider
    {
    class Program
        {
        static void Main( string[] args )
            {
 
            using( SQLiteConnection cnn = new SQLiteConnection ( "Data Source=foods.db" ) )
                {
                cnn.Open ();
                    SQLiteCommand cmd = new SQLiteCommand ( cnn );
                    cmd.CommandText = "insert into foods values (#id,5,'vodka'); ";
                    SQLiteDataReader dr = cmd.ExecuteReader ();
                    Console.WriteLine ( "Vivod poley tablici" );
                    //for( int i = 0; i < dr.FieldCount; i++ )
                    //  {
                    //  Console.WriteLine ( dr.GetName ( i ) );
                    //  }
                    //Console.WriteLine ( "fields number: '{0}", dr.FieldCount );
 
                    if( dr.HasRows )
                        {
                        while( dr.Read () )
                            {
                            Console.WriteLine ( dr.GetValue (0).ToString ()+'t'+
                                dr.GetValue(1).ToString()+ 't' +
                                dr.GetValue(2).ToString());
                            }
                        }
                    Console.ReadKey ();
                    dr.Close ();
                    }
                }
            }
        }

выдает ошибку

Необработанное исключение типа «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

Цитата
Сообщение от mixon-21
Посмотреть сообщение

какие параметры я недописал???

Если вас интересует конкретно этот вопрос, то ошибка возникает из-за параметра #id, который вы в комманду не передаете.
Если вы хотите получить работоспособный код, то сотрите написанный вами код нафиг, почитайте про SQL и ADO.NET и напишите код заново и правильно. Сейчас у вас написан бред. Команда INSERT не возвращает набора данных, по которому можно пройтись DataReader’ом. А что вы хотели сделать в этом куске кода, одному вам известно.



0



5 / 5 / 3

Регистрация: 05.03.2013

Сообщений: 220

30.07.2014, 23:51

 [ТС]

4

Цитата
Сообщение от Баксофф
Посмотреть сообщение

На какой строке выдает?

выдает на этой строке.

Цитата
Сообщение от mixon-21
Посмотреть сообщение

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-ом?
Напишите корректно SQL-запрос на вставку строки и воспользуйтесь методом ExecuteNonQuery.



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

  1. 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])
)
  1. Step B
    Insert the selected record so that it finds it

  2. 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;
    }
}
  • Home
  • VBForums
  • Visual Basic
  • Database Development
  • [RESOLVED] SQLite — CRUD

  1. Jan 17th, 2023, 11:11 AM


    #1

    The_Hobbyist is offline

    Thread Starter


    Addicted Member


    Resolved [RESOLVED] SQLite — CRUD

    Working with SQLite, sorting out my CRUD functions and data bindings has proven very challenging for me and no doubt frustrating for those offering their guidance. With plenty of help, direction and sample code from the gurus here, I have a project that is coming along. With that said, my project still isn’t adding a new record to the database nor is it editing existing records as it should. My main objective at this point is to sort that out. In an effort to be clear, I will show much of my code here in the first post and as it evolves, I’ll re-share it in the following posts.

    First, I’ll show my database tables along with a few records, just so we’re all on the same page (I’m a visual guy):

    This is the Parent table and is called Gemstones

    ID Primary Key Name HardA HardB DensA DensB Formula CrystallographyID Foreign Key
    1 Acanthite 2.0 2.5 Ag2S 1
    2 Achroite 2.90 3.40 A(D3)G6(T6O18)(BO3)3X3Z 2
    3 Actinolite 5.5 6.0 3.03 3.24 Ca2(Mg,Fe)5Si8O22(OH)2 1
    4 Adamite 3.5 3.5 4.32 4.38 Zn2(AsO4)(OH) 3
    5 Adamite (Cuprian) 3.5 3.5 4.32 4.38 (Zn,Cu)2AsO4OH 4
    6 Adularia 6.0 6.5 2.55 2.63 KAlSi3O8 1
    7 Aegirine 6.0 6.0 3.50 3.60 NaFe3+(Si2O6) 1

    This is a Child table and is called Crystallography

    CrystalID Primary Key CrystalStructure
    1 Monoclinic � Prismatic
    2 Trigonal
    3 Orthorhombic � Dipyramidal
    4 Orthorhombic
    5 Triclinic � Pinacoidal

    I’ve removed some of the non-related code but this is the general idea of what I have going on in the coding department:

    Code:

    Imports System.Data.SQLite
    
    Public Class frmMain
    
        Private dbCon As New SQLiteConnection("Data Source=" & Application.StartupPath & "Database.db;" & "Version=3;New=False;Compressed=True;")
    
        Dim Adapter1 As String = ("SELECT * FROM Gemstones ORDER BY Name ASC")
        Dim Adapter2 As String = ("SELECT * FROM Crystallography ORDER BY CrystalStructure ASC")
    
        Private adGemstones As New SQLiteDataAdapter(Adapter1, dbCon)
        Private adCrystallography As New SQLiteDataAdapter(Adapter2, dbCon)
    
        Private dtGemstones As New DataTable
        Private bsGemstones As New BindingSource
    
        Private dtCrystallography As New DataTable
        Private bsCrystallography As New BindingSource
    
        Dim SQLite_Connect As SQLite.SQLiteConnection
        Dim SQLite_Command As SQLite.SQLiteCommand
    
        'Private My_CommandBuilder As New SQLiteCommandBuilder(adGemstones) With {.QuotePrefix = "[", .QuoteSuffix = "]"}
    
    
    
        Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            Me.DGV.SelectionMode = DataGridViewSelectionMode.FullRowSelect
    
            'dbCon.Open()
    
            SetUpAdapter()
    
            adGemstones.Fill(dtGemstones)
            adCrystallography.Fill(dtCrystallography)
            bsGemstones.DataSource = dtGemstones
            Me.DGV.DataSource = bsGemstones
    
            SetUpBindings()
    
        End Sub
    
    
    
        Private Sub SetUpAdapter()
            Dim parentInsertCommand As New SQLiteCommand("INSERT INTO Gemstones (Name, HardA, HardB, DensA, DensB, Formula) VALUES (@Name, @HardA, @HardB, @DensA, @DensB, @Formula)", dbCon)
            Dim parentUpdateCommand As New SQLiteCommand("UPDATE Gemstones SET Name = @Name, CrystallographyID = @CrystallographyID WHERE Id = @Id", dbCon)
            Dim parentDeleteCommand As New SQLiteCommand("DELETE FROM Gemstones WHERE Id = @Id", dbCon)
    
            With parentInsertCommand.Parameters
                .Add("@Name", DbType.String, 50, "Name")
                .Add("@HardA", DbType.String, 50, "HardA")
                .Add("@HardB", DbType.String, 50, "HardB")
                .Add("@DensA", DbType.String, 50, "DensA")
                .Add("@DensB", DbType.String, 50, "DensB")
                .Add("@Formula", DbType.String, 50, "Formula")
                .Add("@CrystallagraphyID", DbType.Int32, 0, "CrystallographyID")
            End With
    
            With parentUpdateCommand.Parameters
                .Add("@Name", DbType.String, 50, "Name")
                .Add("@HardA", DbType.String, 50, "HardA")
                .Add("@HardB", DbType.String, 50, "HardB")
                .Add("@DensA", DbType.String, 50, "DensA")
                .Add("@DensB", DbType.String, 50, "DensB")
                .Add("@Formula", DbType.String, 50, "Formula")
                .Add("@CrystallagraphyID", DbType.Int32, 0, "CrystallographyID")
                .Add("@Id", DbType.Int32, 0, "Id")
            End With
    
            With parentDeleteCommand.Parameters
                .Add("@Id", DbType.Int32, 0, "Id")
            End With
    
            With adGemstones
                .InsertCommand = parentInsertCommand
                .UpdateCommand = parentUpdateCommand
                .DeleteCommand = parentDeleteCommand
            End With
    
        End Sub
    
    
    
        Private Sub SetUpBindings()
    
            bsGemstones.DataSource = dtGemstones
    
            Me.lblID.DataBindings.Add("Text", bsGemstones, "ID")
            Me.txtName.DataBindings.Add("Text", bsGemstones, "Name")
            Me.txtHardnessA.DataBindings.Add("Text", bsGemstones, "HardA")
            Me.txtHardnessB.DataBindings.Add("Text", bsGemstones, "HardB")
            Me.txtDensityA.DataBindings.Add("Text", bsGemstones, "DensA")
            Me.txtDensityB.DataBindings.Add("Text", bsGemstones, "DensB")
            Me.txtFormula.DataBindings.Add("Text", bsGemstones, "Formula")
    
            Me.cmbCrystalSystem.DataBindings.Add("Selectedvalue", bsGemstones, "CrystallographyID")
            Me.cmbCrystalSystem.DisplayMember = "CrystalStructure"
            Me.cmbCrystalSystem.ValueMember = "CrystalID"
            Me.cmbCrystalSystem.SelectedValue = "CrystalID"
            Me.cmbCrystalSystem.DataSource = dtCrystallography
    
            Me.DGV.DataSource = bsGemstones
    
        End Sub
    
    
    
        Private Sub btnSaveNew_Click(sender As Object, e As EventArgs) Handles btnSaveNew.Click
    
            Dim NewRecordName As String = Me.txtName.Text
    
            If MessageBox.Show(String.Format("Do you want to save a new record for " & NewRecordName & "?"), "Confirmation", MessageBoxButtons.YesNo) = DialogResult.Yes Then
    
                bsGemstones.EndEdit()
                adGemstones.Update(dtGemstones)
    
                dtGemstones = New DataTable
                adGemstones.Fill(dtGemstones)
                bsGemstones.DataSource = dtGemstones
                Me.DGV.DataSource = bsGemstones
    
                MessageBox.Show("The new record has been saved successfully")
    
            Else
    
                MessageBox.Show("The new record creation has been canceled")
    
            End If
    
        End Sub
    
    
    
        Private Sub btnEdit_Click(sender As Object, e As EventArgs) Handles btnEdit.Click
    
            Dim SelectedRow As DataGridViewRow
            SelectedRow = DGV.CurrentRow
            Dim ID As Integer = SelectedRow.Cells(0).Value
    
            If MessageBox.Show(String.Format("Do you want to save the edits to {0}", SelectedRow.Cells("Name").Value), "Confirmation", MessageBoxButtons.YesNo) = DialogResult.Yes Then
    
                bsGemstones.EndEdit()
                adGemstones.Update(dtGemstones)
    
                dtGemstones = New DataTable
                adGemstones.Fill(dtGemstones)
                bsGemstones.DataSource = dtGemstones
                Me.DGV.DataSource = bsGemstones
    
                MessageBox.Show("The edit was successful")
    
            Else
    
                MessageBox.Show("The edit has been canceled")
    
            End If
    
        End Sub
    
    
    
        Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
    
            Dim SelectedRow As DataGridViewRow
            SelectedRow = DGV.CurrentRow
            Dim ID As Integer = SelectedRow.Cells(0).Value
    
            If MessageBox.Show(String.Format("Do you want to delete {0}", SelectedRow.Cells("Name").Value), "Confirmation", MessageBoxButtons.YesNo) = DialogResult.Yes Then
    
                If Me.DGV.SelectedRows.Count > 0 Then
                    bsGemstones.RemoveCurrent()
                    bsGemstones.EndEdit()
                    adGemstones.Update(dtGemstones)
    
                    MessageBox.Show("Delete was successful")
    
                End If
    
            Else
    
                MessageBox.Show("Delete was canceled")
    
            End If
    
        End Sub
    
    
        Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
            Me.Close()
        End Sub
    
    
    End Class

    With that out of the way I want to address my questions and issues with the code I’ve shared. They are as follows:

    • The Command Builder line:

      Private My_CommandBuilder As New SQLiteCommandBuilder(adGemstones) With {.QuotePrefix = «[«, .QuoteSuffix = «]»}

      I had this line in an earlier rendition of my project. It appears to be a leftover but I am hesitant to remove it. I realize that it is building a command but the application doesn’t seem to need it in order to run. As a result I have block deleted this line of code out of my project for the time being.

      Goal: to understand what this line does and why I need it (if I do).

    • The Opening of the database call:

      dbCon.Open()

      This line doesn’t seem to effect the application. It came to my in some sample code and when I was trying to deconstruct that code so as to better understand it, I was stumped as to why this line was there. So I have block deleted the line out of my code and the application appears to run as it should? I understand that it is calling to open the database but I don’t understand why it would do so at this point in the code.

      Goal: to understand why this line should be there (if it should be there).

    • The «Save New» function doesn’t work:

      When trying to write code that would create a new record and save it to the database, some sample code was written for me in an effort to put me on the right track. Two simple lines were put into a button click event, those two lines were:

      bsGemstones.EndEdit()
      adGemstones.Update(dtGemstones)

      This does not appear to save a new record to the database. I did have some luck with this code when the database was just a single table structure however, it worked more like an EDIT function. What I mean by that is that the button click event would alter whichever line was highlighted in the DGV and then write that alteration to the database file. It didn’t seem to create a new record then nor does it now. In fact, now that I have moved to a two table database, the second line (update) throws an error. That error is:

      System.Data.SQLite.SQLiteException: ‘unknown error
      Insufficient parameters supplied to the command’

      Goal: To be able to create a new record and write it to the database file with the button click event.

    • The «Edit» function doesn’t work:

      As stated above, when some sample code came my way for saving a new record, that code acted more like an edit record function. So, I was using it in a button click event to edit records in my database. It was simple, highlight a line in the DGV, enter the new data into the corresponding text/combo boxes and click the button. When I was working with a single table database, this code appeared to worked. Now that I am working with a two table database, this code throws an error. Since this code is exactly the same as the «Save New» function above, it throws the same error as listed above.

      Goal: To be able to highlight a DGV line, enter alternate data into the data bound form objects (text/combo boxes) and re-write that record with a button click event, using the new data from the text/combo boxes.

    • The DGV population:

      With the above code, my DGV shows the «CrystalographyID» field from the parent table («Gemstones») table however, I can’t seem to find a way for the DGV to also display the «CrystalStructure» field from the child table (Crystalography) at the same time. I’m nearly certain this was shown to me at some point but I can’t seem to find that example now.

      Goal: to have the DGV display fields from both the parent and child tables simultaneously. This is not a main objective at this time but is more of a curiosity. Frankly, I haven’t truly decided whether the grid will display the mentioned data in the finished application or not. For now, this is merely a curiosity as previously stated.


  2. Jan 17th, 2023, 12:37 PM


    #2

    Re: SQLite — CRUD

    are you sure that these values …

    Code:

      .Add("@HardA", DbType.String, 50, "HardA")
                .Add("@HardB", DbType.String, 50, "HardB")
                .Add("@DensA", DbType.String, 50, "DensA")
                .Add("@DensB", DbType.String, 50, "DensB")

    are strings ?

    in your visual Table they look like double or decimal values. also I would use a Treeview to display the Data not a Datagridview
    but that is just my opinion

    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 — 3900 were counted. with Baby Callas it’s 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.


  3. Jan 17th, 2023, 01:16 PM


    #3

    The_Hobbyist is offline

    Thread Starter


    Addicted Member


    Re: SQLite — CRUD

    Quote Originally Posted by ChrisE
    View Post

    are you sure that these values …

    Code:

      .Add("@HardA", DbType.String, 50, "HardA")
                .Add("@HardB", DbType.String, 50, "HardB")
                .Add("@DensA", DbType.String, 50, "DensA")
                .Add("@DensB", DbType.String, 50, "DensB")

    are strings ?

    in your visual Table they look like double or decimal values.

    Noted and corrected to specify decimal as shown below:

    Code:

            With parentInsertCommand.Parameters
                .Add("@Name", DbType.String, 50, "Name")
                .Add("@HardA", DbType.Decimal, 10, "HardA")
                .Add("@HardB", DbType.Decimal, 10, "HardB")
                .Add("@DensA", DbType.Decimal, 10, "DensA")
                .Add("@DensB", DbType.Decimal, 10, "DensB")
                .Add("@Formula", DbType.String, 50, "Formula")
                .Add("@CrystallagraphyID", DbType.Int32, 0, "CrystallographyID")
            End With
    
            With parentUpdateCommand.Parameters
                .Add("@Name", DbType.String, 50, "Name")
                .Add("@HardA", DbType.Decimal, 10, "HardA")
                .Add("@HardB", DbType.Decimal, 10, "HardB")
                .Add("@DensA", DbType.Decimal, 10, "DensA")
                .Add("@DensB", DbType.Decimal, 10, "DensB")
                .Add("@Formula", DbType.String, 50, "Formula")
                .Add("@CrystallagraphyID", DbType.Int32, 0, "CrystallographyID")
                .Add("@Id", DbType.Int32, 0, "Id")
            End With

    Thank you.


  4. Jan 17th, 2023, 01:59 PM


    #4

    Re: SQLite — CRUD

    Where to start, lol

    The dbCon.Open isn’t necessary if your only using SQLiteDataadapters. The dataadapter will open the connection for you. But if you use a SQLiteCommand you have to open the connection yourself.

    You only need one button to save any changes whether it’s Add/Edit/Delete or several of each.

    Code:

        Private Sub btnSaveNew_Click(sender As Object, e As EventArgs) Handles btnSaveNew.Click
    
               If MessageBox.Show(String.Format("Do you want to save a new record for " & NewRecordName & "?"), "Confirmation", MessageBoxButtons.YesNo) = DialogResult.Yes Then
    
                bsGemstones.EndEdit()
                adGemstones.Update(dtGemstones)
    
                
                MessageBox.Show("The new record has been saved successfully")
    
            Else
    
                MessageBox.Show("The new record creation has been canceled")
    
            End If
    
        End Sub

    That’s all you need.


  5. Jan 17th, 2023, 02:19 PM


    #5

    Re: SQLite — CRUD

    Next,

    Edit/Update error tells you exactly what’s wrong.

    System.Data.SQLite.SQLiteException: ‘unknown error
    Insufficient parameters supplied to the command’

    Thought actually it looks like your using more parameters than fields in the command statements. The point is the number of fields versus the number of parameters most be correct.

    Your Update command is only updating two fields. Your Insert command doesn’t include the «CrystallagraphyID» field.

    Yes we have been over how to store an ID but display the description.

    I’ll repost this example, pay attention to how the FormulaComboBox is setup in SetUpBinding.

    Code:

    Imports System.Data.SQLite
    
    Public Class Form5
        Private con As New SQLiteConnection("Data Source= C:AJunk2019Rocks.db;Version=3")
        Private WithEvents scienceAdapter As New SQLiteDataAdapter("select Id, Name, ChemistryID From ScientificData", con)
        Private WithEvents chemistryAdapter As New SQLiteDataAdapter("select ID, ChemicalFormula From ChemistryData", con)
    
        Private scienceDataTable As New DataTable
        Private chemistryDataTable As New DataTable
    
        Private WithEvents scienceBindingsource As New BindingSource
    
        Private Sub Form5_Load(sender As Object, e As EventArgs) Handles Me.Load
    
            con.Open()
    
            SetUpAdapter()
    
            scienceAdapter.Fill(scienceDataTable)
            chemistryAdapter.Fill(chemistryDataTable)
    
            SetUpBindings()
        End Sub
    
        Private Sub SetUpAdapter()
            Dim parentInsertCommand As New SQLiteCommand("INSERT INTO scientificdata (Name,ChemistryId) VALUES (@Name, @ChemistryId)", con)
            Dim parentUpdateCommand As New SQLiteCommand("UPDATE scientificdata SET Name = @Name, chemistryId = @ChemistryId WHERE Id = @Id", con)
            Dim parentDeleteCommand As New SQLiteCommand("DELETE FROM scientificdata WHERE Id = @Id", con)
    
            With parentInsertCommand.Parameters
                .Add("@Name", DbType.String, 50, "Name")
                .Add("@ChemistryId", DbType.Int32, 0, "ChemistryId")
            End With
    
            With parentUpdateCommand.Parameters
                .Add("@Name", DbType.String, 50, "Name")
                .Add("@ChemistryId", DbType.Int32, 0, "ChemistryId")
                .Add("@Id", DbType.Int32, 0, "Id")
            End With
    
            With parentDeleteCommand.Parameters
                .Add("@Id", DbType.Int32, 0, "Id")
            End With
    
            With scienceAdapter
                .InsertCommand = parentInsertCommand
                .UpdateCommand = parentUpdateCommand
                .DeleteCommand = parentDeleteCommand
            End With
        End Sub
    
        Private Sub SetUpBindings()
    
            scienceBindingsource.DataSource = scienceDataTable
            Me.BindingNavigator1.BindingSource = scienceBindingsource
    
            Me.IdTextBox.DataBindings.Add("Text", scienceBindingsource, "ID")
            Me.NameTextBox.DataBindings.Add("Text", scienceBindingsource, "Name")
    
    
            Me.FormulaComboBox.DataBindings.Add("selectedvalue", scienceBindingsource, "chemistryid")   ' Notice I use the combobox "selectedvalue" property NOT the Text property
    
            Me.FormulaComboBox.DisplayMember = "Chemicalformula"
            Me.FormulaComboBox.ValueMember = "ID"
            Me.FormulaComboBox.SelectedValue = "ID"
            Me.FormulaComboBox.DataSource = chemistryDataTable
    
            Me.scienceDataGridView.DataSource = scienceBindingsource
    
    
        End Sub
    
        Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
            scienceBindingsource.EndEdit()
            scienceAdapter.Update(scienceDataTable)
        End Sub
    End Clas

    This example just uses a standard combobox, not a DatagridviewCombobox. You keep switching between updating the data from the grid and updating using Textboxes/combobox. Though I did also show you how to setup both kinds of Comboboxes. I’ll if I can find the dgv example.

    Edit: Look at post #2 here https://www.vbforums.com/showthread….97#post5591897

    Last edited by wes4dbt; Jan 17th, 2023 at 02:59 PM.


  6. Jan 17th, 2023, 02:55 PM


    #6

    Re: SQLite — CRUD

    The Command Builder line:

    Private My_CommandBuilder As New SQLiteCommandBuilder(adGemstones) With {.QuotePrefix = «[«, .QuoteSuffix = «]»}

    I had this line in an earlier rendition of my project. It appears to be a leftover but I am hesitant to remove it. I realize that it is building a command but the application doesn’t seem to need it in order to run. As a result I have block deleted this line of code out of my project for the time being.

    Goal: to understand what this line does and why I need it (if I do).

    If you use a Commandbuilder then you don’t need to manually setup the dataadapter Insert/Update/Delete commands, it will do that for you.

    You wouldn’t need this,

    Code:

        Private Sub SetUpAdapter()
            Dim parentInsertCommand As New SQLiteCommand("INSERT INTO Gemstones (Name, HardA, HardB, DensA, DensB, Formula) VALUES (@Name, @HardA, @HardB, @DensA, @DensB, @Formula)", dbCon)
            Dim parentUpdateCommand As New SQLiteCommand("UPDATE Gemstones SET Name = @Name, CrystallographyID = @CrystallographyID WHERE Id = @Id", dbCon)
            Dim parentDeleteCommand As New SQLiteCommand("DELETE FROM Gemstones WHERE Id = @Id", dbCon)
    
            With parentInsertCommand.Parameters
                .Add("@Name", DbType.String, 50, "Name")
                .Add("@HardA", DbType.String, 50, "HardA")
                .Add("@HardB", DbType.String, 50, "HardB")
                .Add("@DensA", DbType.String, 50, "DensA")
                .Add("@DensB", DbType.String, 50, "DensB")
                .Add("@Formula", DbType.String, 50, "Formula")
                .Add("@CrystallagraphyID", DbType.Int32, 0, "CrystallographyID")
            End With
    
            With parentUpdateCommand.Parameters
                .Add("@Name", DbType.String, 50, "Name")
                .Add("@HardA", DbType.String, 50, "HardA")
                .Add("@HardB", DbType.String, 50, "HardB")
                .Add("@DensA", DbType.String, 50, "DensA")
                .Add("@DensB", DbType.String, 50, "DensB")
                .Add("@Formula", DbType.String, 50, "Formula")
                .Add("@CrystallagraphyID", DbType.Int32, 0, "CrystallographyID")
                .Add("@Id", DbType.Int32, 0, "Id")
            End With
    
            With parentDeleteCommand.Parameters
                .Add("@Id", DbType.Int32, 0, "Id")
            End With
    
            With adGemstones
                .InsertCommand = parentInsertCommand
                .UpdateCommand = parentUpdateCommand
                .DeleteCommand = parentDeleteCommand
            End With
    
        End Sub

    It’s a good thing to learn to write your own commands, the commandbuilder has it’s limits. Not sure this is something you need to be tackling right now. You could always come back later after you have the system functioning and then write the commands manually. But your are very close to having the command setup correctly. It’s your choice.


  7. Jan 17th, 2023, 03:01 PM


    #7

    Re: SQLite — CRUD

    BTW — Please start asking specific questions, not 10 at a time. It’ll make it easier to answer and easier for you to understand the reply.


  8. Jan 17th, 2023, 03:12 PM


    #8

    The_Hobbyist is offline

    Thread Starter


    Addicted Member


    Re: SQLite — CRUD

    Quote Originally Posted by wes4dbt
    View Post

    BTW — Please start asking specific questions, not 10 at a time. It’ll make it easier to answer and easier for you to understand the reply.

    Absolutely! Understood. I wanted to start this thread off in such a way as to outline everything I have going on, just in case they are connected and I didn’t realize it. I’m trying to get better at being less «all over the place». Moving forward, focus is the key.

    Thanks for your time today. I’m off to my day job now and will look at the above posts later tonight. I’m sure I’ll have questions — I’ll try to limit my posts to one specific question at a time as instructed.

    For the record, I didn’t even realize until after reading your post above just now that there was a difference between updating from the grid or the text/combo boxes. I’ll have to re-read this when I get off work. Furthermore, I was under the assumption that I would need different code for each of the «Save New», «Edit» or «Delete». I obviously don’t understand how to properly utilize the code:

    Code:

        Private Sub btnSaveNew_Click(sender As Object, e As EventArgs) Handles btnSaveNew.Click
    
               If MessageBox.Show(String.Format("Do you want to save a new record for " & NewRecordName & "?"), "Confirmation", MessageBoxButtons.YesNo) = DialogResult.Yes Then
    
                bsGemstones.EndEdit()
                adGemstones.Update(dtGemstones)
    
                
                MessageBox.Show("The new record has been saved successfully")
    
            Else
    
                MessageBox.Show("The new record creation has been canceled")
    
            End If
    
        End Sub

    I’m sure I’ll have questions. I just wanted to acknowledge your help and thank you for it. As I said, I’ll be back later. Thank you again!


  9. Jan 17th, 2023, 03:40 PM


    #9

    Re: SQLite — CRUD

    For the record, I didn’t even realize until after reading your post above just now that there was a difference between updating from the grid or the text/combo boxes. I’ll have to re-read this when I get off work. Furthermore, I was under the assumption that I would need different code for each of the «Save New», «Edit» or «Delete». I obviously don’t understand how to properly utilize the code:

    You misunderstand. The DataAdapter doesn’t care if the data is bound to a dgv or Textboxes. It all has to do with the DataTable. Each datatable row of data (or record) has a RowState property. When you call the «Update» method on the dataadapter it goes through each row in the datatable and checks the RowState. If the rowstate is Unxhanged then it doesn’t do anything to that record, if the rowstate is «Added» then it adds the row to the database table, if the Rowstate is «Deleted» then it deletes that row, if the rowstate is «Modified» then it updates the row. When you modify the data in a bound control, the underlying datatable is also modified.

    So, the DataAdapter doesn’t care what was used the modify the datatable.

    The difference I was talking about is what’s necessary to setup the combobox properly so you get the data you want.

    Last edited by wes4dbt; Jan 17th, 2023 at 03:55 PM.


  10. Jan 17th, 2023, 09:33 PM


    #10

    The_Hobbyist is offline

    Thread Starter


    Addicted Member


    Re: SQLite — CRUD

    Quote Originally Posted by wes4dbt
    View Post

    …it looks like your using more parameters than fields in the command statements. The point is the number of fields versus the number of parameters most be correct.

    I think I understand… While defining the commands, I failed to include all of the fields that were set out as parameters. I believe that I have this sorted out now. The code below now has all of my columns from the parent table listed in the command and the parameters however, I’m still getting the same error (System.Data.SQLite.SQLiteException: unknown error Insufficient parameters supplied to the command) on the same line: adGemstones.Update(dtGemstones)

    Currently my code for the INSERT command looks like this (I’m focused on the INSERT right now, one thing at a time):

    Code:

         Private Sub SetUpAdapter()
    
            Dim parentInsertCommand As New SQLiteCommand("INSERT INTO Gemstones (ID, Name, HardA, HardB, DensA, DensB, Formula, CrystallographyID) VALUES (@ID, @Name, @HardA, @HardB, @DensA, @DensB, @Formula, @CrystallographyID)", dbCon)
    
            With parentInsertCommand.Parameters
                .Add("@ID", DbType.Int32, 0, "ID")
                .Add("@Name", DbType.String, 50, "Name")
                .Add("@HardA", DbType.Decimal, 10, "HardA")
                .Add("@HardB", DbType.Decimal, 10, "HardB")
                .Add("@DensA", DbType.Decimal, 10, "DensA")
                .Add("@DensB", DbType.Decimal, 10, "DensB")
                .Add("@Formula", DbType.String, 50, "Formula")
                .Add("@CrystallographyID", DbType.Int32, 0, "CrystallographyID")
            End With
    
            With adGemstones
                .InsertCommand = parentInsertCommand
            End With
    
        End Sub

    Where the error occurs:

    Code:

        Private Sub btnSaveNew_Click(sender As Object, e As EventArgs) Handles btnSaveNew.Click
    
            Dim NewRecordName As String = Me.txtName.Text
    
            If MessageBox.Show(String.Format("Do you want to save a new record for " & NewRecordName & "?"), "Confirmation", MessageBoxButtons.YesNo) = DialogResult.Yes Then
    
                bsGemstones.EndEdit()
                adGemstones.Update(dtGemstones)   <----- ERROR HAPPENS HERE
    
                MessageBox.Show("The new record has been saved successfully")
    
            Else
    
                MessageBox.Show("The new record creation has been canceled")
    
            End If
    
        End Sub

    What am I missing here?


  11. Jan 17th, 2023, 10:14 PM


    #11

    Re: SQLite — CRUD

    «ID» is an Autonumber field so don’t include it in the Insert statement.

    Try that, see if it solves your problem.


  12. Jan 17th, 2023, 10:20 PM


    #12

    The_Hobbyist is offline

    Thread Starter


    Addicted Member


    Re: SQLite — CRUD

    Quote Originally Posted by wes4dbt
    View Post

    «ID» is an Autonumber field so don’t include it in the Insert statement.

    Try that, see if it solves your problem.

    I actually thought of that and have tried it both ways. It errors at the same point with the same error either way…


  13. Jan 17th, 2023, 10:45 PM


    #13

    Re: SQLite — CRUD

    Why have you removed the dataadapter UpdateCommand aand DeleteCommand. I just tested and I get an error when I try to add a new record if there isn’t a valid UpdateCommand for the dataadapter. But it’s not the same error as you say your getting.

    This works,

    Code:

        Private Sub SetUpAdapter()
            Dim parentInsertCommand As New SQLiteCommand("INSERT INTO scientificdata (Name, Density, ChemistryId) VALUES (@Name, @Density, @ChemistryId)", con)
            Dim parentUpdateCommand As New SQLiteCommand("UPDATE scientificdata SET Name = @Name, Density = @Density, chemistryId = @ChemistryId WHERE Id = @Id", con)
            Dim parentDeleteCommand As New SQLiteCommand("DELETE FROM scientificdata WHERE Id = @Id", con)
    
            With parentInsertCommand.Parameters
                .Add("@Name", DbType.String, 50, "Name")
                .Add("@ChemistryId", DbType.Int32, 0, "ChemistryId")
                .Add("@Density", DbType.Decimal, 10, "Density")
            End With
    
            With parentUpdateCommand.Parameters
                .Add("@Name", DbType.String, 50, "Name")
                .Add("@ChemistryId", DbType.Int32, 0, "ChemistryId")
                .Add("@Density", DbType.Decimal, 0, "Density")
                .Add("@Id", DbType.Int32, 0, "Id")
            End With
    
            With parentDeleteCommand.Parameters
                .Add("@Id", DbType.Int32, 0, "Id")
            End With
    
            With scienceAdapter
                .InsertCommand = parentInsertCommand
                .UpdateCommand = parentUpdateCommand
                .DeleteCommand = parentDeleteCommand
            End With
        End Sub

    HOW are you trying to add a new record? Are you calling the «AddNew» method on bsGemstones?

    Post all relevant code. I’d suggest you stop making major changes to your code everytime. If it needed massive changes we would have told you. It’s to hard to solve problems that way.

    Last edited by wes4dbt; Jan 17th, 2023 at 10:48 PM.


  14. Jan 17th, 2023, 10:57 PM


    #14

    The_Hobbyist is offline

    Thread Starter


    Addicted Member


    Re: SQLite — CRUD

    I removed the UPDATE and DELETE commands only from the code I shared, in an effort to focus on just the INSERT command. In my project, both of these commands are still present.

    I think this is the code your asking me for? This is how I thought I would insert a new record? Perhaps I misunderstood a previous post where you said that this would be all I need to INSERT/UPDATE/DELETE.

    Code:

        Private Sub btnSaveNew_Click(sender As Object, e As EventArgs) Handles btnSaveNew.Click
    
            Dim NewRecordName As String = Me.txtName.Text
    
            If MessageBox.Show(String.Format("Do you want to save a new record for " & NewRecordName & "?"), "Confirmation", MessageBoxButtons.YesNo) = DialogResult.Yes Then
    
                bsGemstones.EndEdit()
                adGemstones.Update(dtGemstones)
    
                MessageBox.Show("The new record has been saved successfully")
    
            Else
    
                MessageBox.Show("The new record creation has been canceled")
    
            End If
    
        End Sub


  15. Jan 17th, 2023, 11:02 PM


    #15

    Re: SQLite — CRUD

    No that doesn’t tell me anything about what method your using to add a new record. Just post all your code in the form.

    What I mean. Do you have an «ADD» button you click when you want to a a new record or do you use a BindingNavigator Add button. Are you trying to Add a record using the DGV? Where is the bindingsource «AddNew» method being called.

    Last edited by wes4dbt; Jan 17th, 2023 at 11:06 PM.


  16. Jan 17th, 2023, 11:05 PM


    #16

    The_Hobbyist is offline

    Thread Starter


    Addicted Member


    Re: SQLite — CRUD

    Code:

    Imports System.Data.SQLite
    
    Public Class frmMain
    
        Private dbCon As New SQLiteConnection("Data Source=" & Application.StartupPath & "Database.db;" & "Version=3;New=False;Compressed=True;")
    
        Dim Adapter1 As String = ("SELECT ID, Name, HardA, HardB, DensA, DensB, Formula, CrystallographyID FROM Gemstones ORDER BY Name ASC")
        Dim Adapter2 As String = ("SELECT CrystalID, CrystalStructure FROM Crystallography ORDER BY CrystalID ASC")
    
        Private adGemstones As New SQLiteDataAdapter(Adapter1, dbCon)
        Private adCrystallography As New SQLiteDataAdapter(Adapter2, dbCon)
    
        Private dtGemstones As New DataTable
        Private bsGemstones As New BindingSource
    
        Private dtCrystallography As New DataTable
        Private bsCrystallography As New BindingSource
    
        Dim SQLite_Connect As SQLite.SQLiteConnection
        Dim SQLite_Command As SQLite.SQLiteCommand
    
    
        Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            SetUpAdapter()
    
            adGemstones.Fill(dtGemstones)
            adCrystallography.Fill(dtCrystallography)
            bsGemstones.DataSource = dtGemstones
            Me.DGV.DataSource = bsGemstones
    
            SetUpBindings()
    
        End Sub
    
    
    
        Private Sub SetUpAdapter()
            Dim parentInsertCommand As New SQLiteCommand("INSERT INTO Gemstones (Name, HardA, HardB, DensA, DensB, Formula, CrystallographyID) VALUES (@Name, @HardA, @HardB, @DensA, @DensB, @Formula, @CrystallographyID)", dbCon)
            Dim parentUpdateCommand As New SQLiteCommand("UPDATE Gemstones SET Name = @Name, HardA = @HardA, HardB = @HardB, DensA = @DensB, Formula = @Formula, CrystallographyID = @CrystallographyID WHERE Id = @Id", dbCon)
            Dim parentDeleteCommand As New SQLiteCommand("DELETE FROM Gemstones WHERE Id = @Id", dbCon)
    
            With parentInsertCommand.Parameters
                .Add("@ID", DbType.Int32, 0, "ID")
                .Add("@Name", DbType.String, 50, "Name")
                .Add("@HardA", DbType.Decimal, 10, "HardA")
                .Add("@HardB", DbType.Decimal, 10, "HardB")
                .Add("@DensA", DbType.Decimal, 10, "DensA")
                .Add("@DensB", DbType.Decimal, 10, "DensB")
                .Add("@Formula", DbType.String, 50, "Formula")
                .Add("@CrystallographyID", DbType.Int32, 0, "CrystallographyID")
            End With
    
            With parentUpdateCommand.Parameters
                .Add("@Name", DbType.String, 50, "Name")
                .Add("@HardA", DbType.Decimal, 10, "HardA")
                .Add("@HardB", DbType.Decimal, 10, "HardB")
                .Add("@DensA", DbType.Decimal, 10, "DensA")
                .Add("@DensB", DbType.Decimal, 10, "DensB")
                .Add("@Formula", DbType.String, 50, "Formula")
                .Add("@CrystallographyID", DbType.Int32, 0, "CrystallographyID")
            End With
    
            With parentDeleteCommand.Parameters
                .Add("@ID", DbType.Int32, 50, "ID")
            End With
    
            With adGemstones
                .InsertCommand = parentInsertCommand
                .UpdateCommand = parentUpdateCommand
                .DeleteCommand = parentDeleteCommand
            End With
    
        End Sub
    
    
    
        Private Sub SetUpBindings()
    
            bsGemstones.DataSource = dtGemstones
            Me.lblID.DataBindings.Add("Text", bsGemstones, "ID")
            Me.txtName.DataBindings.Add("Text", bsGemstones, "Name")
            Me.txtHardnessA.DataBindings.Add("Text", bsGemstones, "HardA")
            Me.txtHardnessB.DataBindings.Add("Text", bsGemstones, "HardB")
            Me.txtDensityA.DataBindings.Add("Text", bsGemstones, "DensA")
            Me.txtDensityB.DataBindings.Add("Text", bsGemstones, "DensB")
            Me.txtFormula.DataBindings.Add("Text", bsGemstones, "Formula")
            Me.cmbCrystalSystem.DataBindings.Add("Selectedvalue", bsGemstones, "CrystallographyID")
            Me.cmbCrystalSystem.DisplayMember = "CrystalStructure"
            Me.cmbCrystalSystem.ValueMember = "CrystalID"
            Me.cmbCrystalSystem.SelectedValue = "CrystalID"
            Me.cmbCrystalSystem.DataSource = dtCrystallography
    
            Me.DGV.DataSource = bsGemstones
    
        End Sub
    
    
    
        Private Sub btnSaveNew_Click(sender As Object, e As EventArgs) Handles btnSaveNew.Click
    
            Dim NewRecordName As String = Me.txtName.Text
    
            If MessageBox.Show(String.Format("Do you want to save a new record for " & NewRecordName & "?"), "Confirmation", MessageBoxButtons.YesNo) = DialogResult.Yes Then
    
                bsGemstones.EndEdit()
                adGemstones.Update(dtGemstones)
    
                MessageBox.Show("The new record has been saved successfully")
    
            Else
    
                MessageBox.Show("The new record creation has been canceled")
    
            End If
    
            dtGemstones = New DataTable
            adGemstones.Fill(dtGemstones)
            bsGemstones.DataSource = dtGemstones
    
        End Sub
    
    
        Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
            Me.Close()
        End Sub
    
    End Class

    Last edited by The_Hobbyist; Jan 17th, 2023 at 11:26 PM.


  17. Jan 17th, 2023, 11:16 PM


    #17

    Re: SQLite — CRUD

    Change this,

    Code:

    Dim parentUpdateCommand As New SQLiteCommand("UPDATE Gemstones SET ID = @ID, Name = @Name, HardA = @HardA, HardB = @HardB, DensA = @DensB, Formula = @Formula, CrystallographyID = @CrystallographyID WHERE Id = @Id", dbCon)
    
    To
    
    Dim parentUpdateCommand As New SQLiteCommand("UPDATE Gemstones SET Name = @Name, HardA = @HardA, HardB = @HardB, DensA = @DensB, Formula = @Formula, CrystallographyID = @CrystallographyID WHERE Id = @Id", dbCon)

    You can’t set the ID

    Also please don’t use «*», type out the field names. I need to see exactly what’s being Selected from the Database. Makes it much easier to check for Typo’s and other things.

    Last edited by wes4dbt; Jan 17th, 2023 at 11:19 PM.


  18. Jan 17th, 2023, 11:23 PM


    #18

    Re: SQLite — CRUD

    I told you before to get rid of this.

    Code:

              Me.DGV.DataSource = bsGemstones
                Me.DGV.Enabled = True
                Me.btnNew.Enabled = True
                Me.btnNew.Visible = True
                Me.btnNew.Location = New Point(13, 20)
                Me.btnSaveNew.Enabled = False
                Me.btnEdit.Enabled = True
                Me.btnDelete.Enabled = True
                Me.btnCancel.Enabled = False
                Me.btnCancel.Visible = False
                Me.btnCancel.Location = New Point(13, 50)


  19. Jan 17th, 2023, 11:24 PM


    #19

    Re: SQLite — CRUD

    And all this,

    Code:

        Private Sub btnEdit_Click(sender As Object, e As EventArgs) Handles btnEdit.Click
    
            Dim SelectedRow As DataGridViewRow
            SelectedRow = DGV.CurrentRow
            Dim ID As Integer = SelectedRow.Cells(0).Value
    
            If MessageBox.Show(String.Format("Do you want to save the edits to {0}", SelectedRow.Cells("Name").Value), "Confirmation", MessageBoxButtons.YesNo) = DialogResult.Yes Then
    
                bsGemstones.EndEdit()
                adGemstones.Update(dtGemstones)
    
                dtGemstones = New DataTable
                adGemstones.Fill(dtGemstones)
                bsGemstones.DataSource = dtGemstones
                Me.DGV.DataSource = bsGemstones
    
                MessageBox.Show("The edit was successful")
    
            Else
    
                MessageBox.Show("The edit has been canceled")
    
            End If
    
        End Sub
    
    
    
        Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
    
            Dim SelectedRow As DataGridViewRow
            SelectedRow = DGV.CurrentRow
            Dim ID As Integer = SelectedRow.Cells(0).Value
    
            If MessageBox.Show(String.Format("Do you want to delete {0}", SelectedRow.Cells("Name").Value), "Confirmation", MessageBoxButtons.YesNo) = DialogResult.Yes Then
    
                If Me.DGV.SelectedRows.Count > 0 Then
    
                    bsGemstones.EndEdit()
                    adGemstones.Update(dtGemstones)
    
                    MessageBox.Show("Delete was successful")
    
                End If
    
            Else
    
                MessageBox.Show("Delete was canceled")
    
            End If
    
        End Sub


  20. Jan 17th, 2023, 11:27 PM


    #20

    Re: SQLite — CRUD

    Post your code after you make these changes and let me know what happens when you try to add a new record.


  21. Jan 17th, 2023, 11:27 PM


    #21

    The_Hobbyist is offline

    Thread Starter


    Addicted Member


    Re: SQLite — CRUD

    OK. I have edited the code in my above post to reflect your requests.


  22. Jan 17th, 2023, 11:28 PM


    #22

    Re: SQLite — CRUD

    Quote Originally Posted by The_Hobbyist
    View Post

    OK. I have edited the code in my above post to reflect your requests.

    And what happened??? Is it a secret. lol

    Wait, why did you edit the code in your post. Make the changes to your code, test, let me know what happens. If there is still a problem, post your current code, explain the problem or error.


  23. Jan 17th, 2023, 11:32 PM


    #23

    The_Hobbyist is offline

    Thread Starter


    Addicted Member


    Re: SQLite — CRUD

    I’m sorry. Moving forward I wont edit previous posts showing code.

    The problem hasn’t changed. Same error at the same line.


  24. Jan 17th, 2023, 11:33 PM


    #24

    Re: SQLite — CRUD


  25. Jan 17th, 2023, 11:36 PM


    #25

    The_Hobbyist is offline

    Thread Starter


    Addicted Member


    Re: SQLite — CRUD

    Code:

    Imports System.Data.SQLite
    
    Public Class frmMain
    
        Private dbCon As New SQLiteConnection("Data Source=" & Application.StartupPath & "Database.db;" & "Version=3;New=False;Compressed=True;")
    
        Dim Adapter1 As String = ("SELECT ID, Name, HardA, HardB, DensA, DensB, Formula, CrystallographyID FROM Gemstones ORDER BY Name ASC")
        Dim Adapter2 As String = ("SELECT CrystalID, CrystalStructure FROM Crystallography ORDER BY CrystalID ASC")
    
        Private adGemstones As New SQLiteDataAdapter(Adapter1, dbCon)
        Private adCrystallography As New SQLiteDataAdapter(Adapter2, dbCon)
    
        Private dtGemstones As New DataTable
        Private bsGemstones As New BindingSource
    
        Private dtCrystallography As New DataTable
        Private bsCrystallography As New BindingSource
    
        Dim SQLite_Connect As SQLite.SQLiteConnection
        Dim SQLite_Command As SQLite.SQLiteCommand
    
    
        Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            SetUpAdapter()
    
            adGemstones.Fill(dtGemstones)
            adCrystallography.Fill(dtCrystallography)
            bsGemstones.DataSource = dtGemstones
            Me.DGV.DataSource = bsGemstones
    
            SetUpBindings()
    
        End Sub
    
    
    
        Private Sub SetUpAdapter()
            Dim parentInsertCommand As New SQLiteCommand("INSERT INTO Gemstones (Name, HardA, HardB, DensA, DensB, Formula, CrystallographyID) VALUES (@Name, @HardA, @HardB, @DensA, @DensB, @Formula, @CrystallographyID)", dbCon)
            Dim parentUpdateCommand As New SQLiteCommand("UPDATE Gemstones SET Name = @Name, HardA = @HardA, HardB = @HardB, DensA = @DensB, Formula = @Formula, CrystallographyID = @CrystallographyID WHERE Id = @Id", dbCon)
            Dim parentDeleteCommand As New SQLiteCommand("DELETE FROM Gemstones WHERE Id = @Id", dbCon)
    
            With parentInsertCommand.Parameters
                .Add("@ID", DbType.Int32, 0, "ID")
                .Add("@Name", DbType.String, 50, "Name")
                .Add("@HardA", DbType.Decimal, 10, "HardA")
                .Add("@HardB", DbType.Decimal, 10, "HardB")
                .Add("@DensA", DbType.Decimal, 10, "DensA")
                .Add("@DensB", DbType.Decimal, 10, "DensB")
                .Add("@Formula", DbType.String, 50, "Formula")
                .Add("@CrystallographyID", DbType.Int32, 0, "CrystallographyID")
            End With
    
            With parentUpdateCommand.Parameters
                .Add("@Name", DbType.String, 50, "Name")
                .Add("@HardA", DbType.Decimal, 10, "HardA")
                .Add("@HardB", DbType.Decimal, 10, "HardB")
                .Add("@DensA", DbType.Decimal, 10, "DensA")
                .Add("@DensB", DbType.Decimal, 10, "DensB")
                .Add("@Formula", DbType.String, 50, "Formula")
                .Add("@CrystallographyID", DbType.Int32, 0, "CrystallographyID")
            End With
    
            With parentDeleteCommand.Parameters
                .Add("@ID", DbType.Int32, 50, "ID")
            End With
    
            With adGemstones
                .InsertCommand = parentInsertCommand
                .UpdateCommand = parentUpdateCommand
                .DeleteCommand = parentDeleteCommand
            End With
    
        End Sub
    
    
    
        Private Sub SetUpBindings()
    
            bsGemstones.DataSource = dtGemstones
            Me.lblID.DataBindings.Add("Text", bsGemstones, "ID")
            Me.txtName.DataBindings.Add("Text", bsGemstones, "Name")
            Me.txtHardnessA.DataBindings.Add("Text", bsGemstones, "HardA")
            Me.txtHardnessB.DataBindings.Add("Text", bsGemstones, "HardB")
            Me.txtDensityA.DataBindings.Add("Text", bsGemstones, "DensA")
            Me.txtDensityB.DataBindings.Add("Text", bsGemstones, "DensB")
            Me.txtFormula.DataBindings.Add("Text", bsGemstones, "Formula")
            Me.cmbCrystalSystem.DataBindings.Add("Selectedvalue", bsGemstones, "CrystallographyID")
            Me.cmbCrystalSystem.DisplayMember = "CrystalStructure"
            Me.cmbCrystalSystem.ValueMember = "CrystalID"
            Me.cmbCrystalSystem.SelectedValue = "CrystalID"
            Me.cmbCrystalSystem.DataSource = dtCrystallography
    
            Me.DGV.DataSource = bsGemstones
    
        End Sub
    
    
    
        Private Sub btnSaveNew_Click(sender As Object, e As EventArgs) Handles btnSaveNew.Click
    
            Dim NewRecordName As String = Me.txtName.Text
    
            If MessageBox.Show(String.Format("Do you want to save a new record for " & NewRecordName & "?"), "Confirmation", MessageBoxButtons.YesNo) = DialogResult.Yes Then
    
                bsGemstones.EndEdit()
                adGemstones.Update(dtGemstones)
    
                MessageBox.Show("The new record has been saved successfully")
    
            Else
    
                MessageBox.Show("The new record creation has been canceled")
    
            End If
    
            dtGemstones = New DataTable
            adGemstones.Fill(dtGemstones)
            bsGemstones.DataSource = dtGemstones
    
        End Sub
    
    
        Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
            Me.Close()
        End Sub
    
    End Class


  26. Jan 17th, 2023, 11:40 PM


    #26

    The_Hobbyist is offline

    Thread Starter


    Addicted Member


    Re: SQLite — CRUD

    If this help at all, this is my entire project in a ZIP file.

    It would appear that the VB Forums website doesn’t allow direct downloading from links? You might have to right click, copy link address and then paste that link address into a new browser window. It’s a link to my personal website where I have the ZIP file stored.

    CRUD.zip

    *** Updated ZIP file as of post #40 ***

    Last edited by The_Hobbyist; Jan 18th, 2023 at 10:26 AM.


  27. Jan 17th, 2023, 11:46 PM


    #27

    Re: SQLite — CRUD

    You were not suppose to remove «Id» from the parameters you create, just don’t Set ID = @ID. You need the @ID param for the Where claus.

    Change it back to,

    Code:

            With parentUpdateCommand.Parameters
                .Add("@Name", DbType.String, 50, "Name")
                .Add("@HardA", DbType.Decimal, 10, "HardA")
                .Add("@HardB", DbType.Decimal, 10, "HardB")
                .Add("@DensA", DbType.Decimal, 10, "DensA")
                .Add("@DensB", DbType.Decimal, 10, "DensB")
                .Add("@Formula", DbType.String, 50, "Formula")
                .Add("@ID",DBType.Int32,0,"ID")

    btw — This is why you always post the current code after making a change.

    Last edited by wes4dbt; Jan 17th, 2023 at 11:50 PM.


  28. Jan 17th, 2023, 11:49 PM


    #28

    The_Hobbyist is offline

    Thread Starter


    Addicted Member


    Re: SQLite — CRUD

    Quote Originally Posted by wes4dbt
    View Post

    You were not suppose to remove «Id» from the parameters you create, just don’t Set ID = @ID. You need the @ID param for the Where clausd.

    Ah! Yes… This now seems to work with that @ID put back in:

    Code:

            With parentUpdateCommand.Parameters
                .Add("@ID", DbType.Int32, 0, "ID")
                .Add("@Name", DbType.String, 50, "Name")
                .Add("@HardA", DbType.Decimal, 10, "HardA")
                .Add("@HardB", DbType.Decimal, 10, "HardB")
                .Add("@DensA", DbType.Decimal, 10, "DensA")
                .Add("@DensB", DbType.Decimal, 10, "DensB")
                .Add("@Formula", DbType.String, 50, "Formula")
                .Add("@CrystallographyID", DbType.Int32, 0, "CrystallographyID")
            End With


  29. Jan 17th, 2023, 11:50 PM


    #29

    The_Hobbyist is offline

    Thread Starter


    Addicted Member


    Re: SQLite — CRUD


  30. Jan 17th, 2023, 11:51 PM


    #30

    The_Hobbyist is offline

    Thread Starter


    Addicted Member


    Re: SQLite — CRUD

    Quote Originally Posted by wes4dbt
    View Post

    btw — This is why you always post the current code after making a change.

    Noted!


  31. Jan 17th, 2023, 11:51 PM


    #31

    Re: SQLite — CRUD

    Thank goodness because I was running out of ideas. Was ready to tell you to use a CommandBuilder and move on.


  32. Jan 17th, 2023, 11:54 PM


    #32

    The_Hobbyist is offline

    Thread Starter


    Addicted Member


    Re: SQLite — CRUD

    Quote Originally Posted by wes4dbt
    View Post

    Thank goodness because I was running out of ideas. Was ready to tell you to use a CommandBuilder and move on.

    LoL…. Well, you have been exceptionally patient and forgiving with me. It is greatly appreciated! I’ll have to send you a beer when this comes to an end…

    In any event, I think for tonight I will call it quits. Tomorrow I will be back with more questions, I’m sure!

    But seriously, I can’t thank you enough. Cheers!


  33. Jan 17th, 2023, 11:55 PM


    #33

    Re: SQLite — CRUD

    I’d still like to know the answer to this,

    Do you have an «ADD» button you click when you want to a a new record or do you use a BindingNavigator Add button. Are you trying to Add a record using the DGV? Where is the bindingsource «AddNew» method being called.

    If you don’t know the AddNew method is being called, that’s Ok. Just tell what you do when you want to add a new record.


  34. Jan 17th, 2023, 11:58 PM


    #34

    The_Hobbyist is offline

    Thread Starter


    Addicted Member


    Re: SQLite — CRUD

    Quote Originally Posted by wes4dbt
    View Post

    I’d still like to know the answer to this,

    If you don’t know the AddNew method is being called, that’s Ok. Just tell what you do when you want to add a new record.

    I’m sorry, I must have missed this question!

    Well, I’m currently entering data into text/combo boxes and then I use an ADD button to create a new record. Likewise, I had envisioned an EDIT ROW and a DELETE ROW button as well.


  35. Jan 18th, 2023, 12:15 AM


    #35

    Re: SQLite — CRUD

    Quote Originally Posted by The_Hobbyist
    View Post

    I’m sorry, I must have missed this question!

    Well, I’m currently entering data into text/combo boxes and then I use an ADD button to create a new record. Likewise, I had envisioned an EDIT ROW and a DELETE ROW button as well.

    This doesn’t make sense to me. These controls are bound, so they will be displaying the current record, they wont be blank. Unless there is no records in the db table. Are you just typing over the data that’s being displayed? If so, your not creating a new record, your just modifying an existing one.


  36. Jan 18th, 2023, 12:20 AM


    #36

    The_Hobbyist is offline

    Thread Starter


    Addicted Member


    Re: SQLite — CRUD

    I made a button that clears the text and combo boxes. I don’t necessarily like it…. Wasn’t sure what was best in this case…


  37. Jan 18th, 2023, 12:21 AM


    #37

    The_Hobbyist is offline

    Thread Starter


    Addicted Member


    Re: SQLite — CRUD

    I’m open to suggestions!


  38. Jan 18th, 2023, 02:01 AM


    #38

    The_Hobbyist is offline

    Thread Starter


    Addicted Member


    Re: SQLite — CRUD

    Now that you got the INSERT/UPDATE working for me, I can see how using these text/combo boxes the way I intend to, is not a great way of going about it. It felt like a good way of doing it until the CRUD started working…lol! You’re right (of course), as it stands now, I am unable to create a new record but rather I am limited to editing whichever record I have highlighted in the DGV at the time.

    I don’t know how to work around this. Entering data into the DGV seems more cumbersome than textboxes and it makes for a pretty unappealing interface if you ask me. It also doesn’t achieve the graphical design that I was shooting for either. Further down the road, I had hoped to use checkboxes as a means of collecting data that would be written to the database as well. It seems to me that these checkboxes, just like the text/combo boxes I am using now, will be bound to the DGV and therefore I will be in the same position with them as I am with the text/combo boxes now — limited to only editing current records.

    I’m going to spend some time thinking this over. Upon first thought, my gut tells me to display the data in the bound form objects like I am doing (to achieve the graphical aspect of the application) but then use a separate «pop up» form to add a new record. The edit and delete functions could run from the main form it would seem. With that said, it was also brought up in previous threads that a pop up window could make things messy.

    If I can’t come up with an idea to alleviate this problem, then I’m sure yourself or another guru here will chime in with some insight. I’m sure there is a preferred method or even a «standard» but my limited experience doesn’t bring anything to mind.


  39. Jan 18th, 2023, 02:47 AM


    #39

    Re: SQLite — CRUD

    Code:

    I made a button that clears the text and combo boxes. I don't necessarily like it.... Wasn't sure what was best in this case...

    Funny I never saw a Button that had code to clear all the control. You trying to pull my leg???

    You don’t need to spend a lot of time thinking about it. We’ve given you the answer before.

    Just add a button control, then in the Button Click event you just call the AddNew method on the bindingsource.

    Code:

        Private Sub AddButton_Click(sender As Object, e As EventArgs) Handles AddButton.Click
            scienceBindingsource.AddNew()
        End Sub

    Last edited by wes4dbt; Jan 18th, 2023 at 03:12 AM.


  40. Jan 18th, 2023, 02:52 AM


    #40

    Re: SQLite — CRUD

    And as i said in your other thread: A ForeignKey is like another column, BUT if correctly set up, it must be provided for an INSERT.

    Code:

    Dim parentInsertCommand As New SQLiteCommand("INSERT INTO Gemstones (Name, HardA, HardB, DensA, DensB, Formula) VALUES (@Name, @HardA, @HardB, @DensA, @DensB, @Formula)", dbCon)

    Your FK to Crytallography is missing!
    That’s why your insert fails!

    The ID of Crystallography MUST exist and be provided to parameters of your INSERT-Command

    Last edited by Zvoni; Tomorrow at 31:69 PM.
    ——————————————————————————————————————————————————————————————————————————————-

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ———————————————————————————
    People call me crazy because i’m jumping out of perfectly fine airplanes.
    ———————————————————————————
    Code is like a joke: If you have to explain it, it’s bad


  • Home
  • VBForums
  • Visual Basic
  • Database Development
  • [RESOLVED] SQLite — CRUD


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

Понравилась статья? Поделить с друзьями:
  • Syntax error что это значит
  • Syntax error скачать
  • System data file access error
  • Syntax error программа
  • System data datarowview как исправить