Skip to main content
edited tags; remove noise
Source Link
t3chb0t
  • 44.7k
  • 9
  • 84
  • 191

Thanks in advance!

Thanks in advance!

Source Link

Try-catch-finally with 'using' in ADO.NET

I want to check if I'm correctly disposing of resources using Ado.NET. I'm not sure when the 'using' statement makes .Dispose() irrelevant.

Please bear in mind I'm aware I shouldn't hardcode my SQL commands, this is just for training purposes.

Thanks in advance!

  internal void CreateTable(string connectionString)
        {
            using (var connection = new SqliteConnection(connectionString))
            {
                using (var tableCmd = connection.CreateCommand())
                {
                    connection.Open();

                    tableCmd.CommandText =
                        @"CREATE TABLE IF NOT EXISTS coding (
                        Id INTEGER PRIMARY KEY AUTOINCREMENT, 
                        Date TEXT, 
                        Duration TEXT
                        )";

                    try
                    {
                        int rowCount = tableCmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        throw;
                    }
                    finally
                    {
                        connection.Dispose();
                        tableCmd.Dispose();
                    }

                }

                // Console.WriteLine($"\n\nDatabase created! \n\n");
            }
        }
    }