Dark Net
Dark Net

Reputation: 1

Can't insert the record to database C# SQLite

I've been struggling with an error related to the database. Basically I have an SQLite db and I want to insert the data, but after I execute the method, no data is written to the db but no errors are shown either. This is my code: The db connection class:

class SqlDb
    {
        public static SQLiteConnection SqLiteConnection;
        public static string DATABASE_WAREHOUSE = "DaneDB.db";

        public static string DATABASE_LACZKA =
            $"Data Source= {DATABASE_WAREHOUSE};Version=3;New=False;Compress=True;";

        public SQLiteConnection Connect()
        {
            try
            {
                SqLiteConnection = new SQLiteConnection(DATABASE_LACZKA);
                SqLiteConnection.Open();

            }
            catch (Exception e)
            {
                MessageBox.Show($"Could not connect to the database {e}");
                throw;
            }

            return SqLiteConnection;
        }

        public void Disconnect()
        {
            SqLiteConnection.Close();
        }

    }

and the inserting method

private void LoadToDb_Click(object sender, EventArgs e)
        {
            Data modelData = new Data();
            SqlDb db = new SqlDb();
            SQLiteConnection sqLiteConnection = db.Connect();
            SQLiteCommand sqLiteCommand = sqLiteConnection.CreateCommand();


            try
            {
                modelData.Name = firstName.Text;
                modelData.Age = Convert.ToInt32(DisplayAge.Text);
                modelData.LastName = LastName.Text;

                sqLiteCommand.CommandText =
                    $"insert into DANE values('{modelData.Name}', '{modelData.LastName}', '{modelData.Age}')"; 

                    db.Disconnect();

            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

I also have the options of database set to:

Build Action: Content
Copy to output directory: Copy always

Upvotes: 0

Views: 134

Answers (1)

Dmitry Grebennikov
Dmitry Grebennikov

Reputation: 434

You forgot to execute this command:

sqLiteCommand.ExecuteNonQuery();

Please refer to documentation: ExecuteNonQuery

Upvotes: 2

Related Questions