C# SQLite работа с базой
Не получается выполнить подряд метод записи и удаления. По отдельности работают. Что я не учёл?
SQLiteConnection connection = new SQLiteConnection("Data Source=MyDB.db; Version=3;");
public void Connect()
{
try
{
connection.Open();
}
catch (SQLiteException ex)
{
MessageBox.Show(ex.Message);
}
}
public void Insert(string Guid, string Name)
{
try
{
Connect();
SQLiteCommand command = new SQLiteCommand();
string query = @"INSERT INTO USERS(Guid,Name) VALUES(@Guid,@Name)";
command.CommandText = query;
command.Connection = connection;
command.Parameters.Add(new SQLiteParameter("@Guid", Guid));
command.Parameters.Add(new SQLiteParameter("@Name", Name));
command.ExecuteNonQuery();
connection.Dispose();
}
catch
{
MessageBox.Show("Error","Wrong Input!", MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
public void Delete (string guid)
{
try
{
Connect();
SQLiteCommand command = new SQLiteCommand();
string query = "DELETE FROM USERS WHERE Guid = '"+ guid +"'";
command.CommandText = query;
command.Connection = connection;
command.ExecuteNonQuery();
connection.Dispose();
}
catch
{
MessageBox.Show("Error", "Wrong Input!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Ответы (1 шт):
Автор решения: aepot
→ Ссылка
Dispose() - это вызов операции разрушения объекта для подготовки к сборке мусора. После вызова Dispose() объект connection использовать нельзя.
Вместо Dispose() используйте Close().
Обработку ошибок так же можно немного улучшить, чтобы знать, что сломалось.
SQLiteConnection connection = new SQLiteConnection("Data Source=MyDB.db; Version=3;");
public void Connect()
{
try
{
connection.Open();
}
catch (SQLiteException ex)
{
MessageBox.Show(ex.Message + "\r\n\r\n" + ex.StackTrace, "Ошибка при подключении!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void Insert(string Guid, string Name)
{
try
{
Connect();
SQLiteCommand command = new SQLiteCommand();
string query = @"INSERT INTO USERS(Guid,Name) VALUES(@Guid,@Name)";
command.CommandText = query;
command.Connection = connection;
command.Parameters.Add(new SQLiteParameter("@Guid", Guid));
command.Parameters.Add(new SQLiteParameter("@Name", Name));
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\r\n\r\n" + ex.StackTrace, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void Delete (string guid)
{
try
{
Connect();
SQLiteCommand command = new SQLiteCommand();
string query = "DELETE FROM USERS WHERE Guid = '"+ guid +"'";
command.CommandText = query;
command.Connection = connection;
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\r\n\r\n" + ex.StackTrace, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}