Transaktioner over flere SqlCommand objecter
Hejsa jeg har lavet følgende klasse til håndtering af mine database kaldpublic class DbHandler
{
private static string ip;
private static string port;
private static string iniCatalog;
private static string userLogin;
private static string userPassword;
public DbHandler(string dbName, string login, string password, string ip, string port)
{
DbHandler.ip = ip;
DbHandler.port = port;
DbHandler.userLogin = login;
DbHandler.userPassword = password;
DbHandler.iniCatalog = dbName;
}
private static SqlConnection NewConnection()
{
return new SqlConnection("workstation id="+ip+";packet size=4096;integrated security=SSPI;data source="+ip+";initial catalog="+iniCatalog+"; user id="+userLogin+"; password="+ userPassword +";");
}
public DataSet doQuery(string sql)
{
DataSet ds = null;
SqlCommand cmd = null;
try
{
cmd = new SqlCommand();
cmd.Connection = NewConnection();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
ds = new DataSet("set");
IDbDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(ds);
if(ds.HasErrors)
{
ds.RejectChanges();
}
else
{
ds.AcceptChanges();
}
if(adapter is IDisposable)
{
((IDisposable) adapter).Dispose();
}
}
catch (SqlException)
{
throw new DataBaseException();
}
finally
{
cmd.Connection.Close();
}
return ds;
}
public int doNonQuery(string sql)
{
int affectedRows = 0;
SqlCommand cmd = null;
try
{
cmd = new SqlCommand();
cmd.Connection = NewConnection();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection.Open();
affectedRows = cmd.ExecuteNonQuery();
}
catch (SqlException)
{
throw new DataBaseException();
}
finally
{
cmd.Connection.Close();
}
return affectedRows;
}
public object doScalar(string sql)
{
object output = null;
SqlCommand cmd = null;
try
{
cmd = new SqlCommand();
cmd.Connection = NewConnection();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection.Open();
output = cmd.ExecuteScalar();
}
catch (SqlException)
{
throw new DataBaseException();
}
finally
{
cmd.Connection.Close();
}
return output;
}
}
nu vil jeg som overskriften siger gerne knytte transaktioner til, så jeg kan lave f.eks. en beginTransaction metode, hvorefter jeg så kan kalde n doQuery, doNonQuery etc. hvorefter jeg kan kalde enten commit eller rollback, mit problem er jeg ikke helt kan overskue hvordan jeg får knytten flere af mine metoder ind i en transaction på den samme connection
håber nogen sidder med den gyldne løsning :)