I have such problem. I've added Transaction service to my SQL class. I get error, when I want to Commit query after its execution. I'll paste the code:
//SOME OF VARIABLES IN CLASS:
private SqlConnection connection;
private SqlCommand newQuery;
private SqlTransaction transaction;
private SqlDataReader result;
//BEGINNING TRANSACTION
public void BeginTransaction(string name)
{
try
{
transaction = connection.BeginTransaction(name);
}
catch
{
MessageBox.Show("Error while beginning transaction " + name);
}
}
//COMMIT TRANSACTION
public void Commit(string text)
{
try
{
transaction.Commit();
}
catch (Exception e)
{
MessageBox.Show("Couldn't commit transaction " + text + "\n\n" + e.ToString());
try
{
transaction.Rollback();
}
catch
{
MessageBox.Show("Couldn't Rollback transaction " + text);
}
}
transaction = null;
}
//EXECUTE QUERY METHOD
private SqlDataReader ExecuteQuery(string query)
{
try
{
if (connection.State == ConnectionState.Closed)
connection.Open();
if (result != null)
result.Close();
newQuery = connection.CreateCommand();
newQuery.CommandText = query;
newQuery.Transaction = transaction;
result = newQuery.ExecuteReader();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
return result;
}
//EXAMPLE FUNCTION WITH TRANSACTION, WHICH OCCURS ERROR:
public bool DoesDatabaseExist(string dbName)
{
BeginTransaction("DoesDatabaseExist");
bool res = ExecuteQuery("SELECT * FROM master.dbo.sysdatabases WHERE name='" + dbName + "';").HasRows;
Commit("Does DB Exist 211");
return res;
}
Afrer running program, I get error, that Commit didn't pass. Like:
Couldn't commit transaction Does DB Exist 211
System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.
I'm studying programming in C# still, so probably it is easy to recognise error. But not for me. Please help.
Before I've added the transaction service, everything was ok, I didn't change or add any of queries or executions of queries. Please help.
Thanks, Mike.