0

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
1
  • 1
    That is a very dangerous and very, very error prone way to concoct SQL queries. Use SQL Parameters always. Your connections also ought to be disposed of when you are done with them Commented Nov 23, 2020 at 16:00

1 Answer 1

2

You forgot to execute this command:

sqLiteCommand.ExecuteNonQuery();

Please refer to documentation: ExecuteNonQuery

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.