Can't insert the record to database C# SQLite

旧巷老猫 提交于 2020-12-15 03:37:26

问题


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:


You forgot to execute this command:

sqLiteCommand.ExecuteNonQuery();

Please refer to documentation: ExecuteNonQuery



来源:https://stackoverflow.com/questions/64971745/cant-insert-the-record-to-database-c-sharp-sqlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!