我有以下錯誤:錯誤在C#TRANSATION和的ExecuteNonQuery
ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized.
出現在功能此錯誤executaComando
我的功能節省:
public void save(string[] arr)//, int lista)
{
SqlConnection conexao = new SqlConnection(WebConfigurationManager.ConnectionStrings["strConexao"].ToString());
conexao.Open();
SqlTransaction trx = conexao.BeginTransaction();
try
{
//Truncate cliente_recurso
BUProjetosDAL dal = new BUProjetosDAL();
dal.excluirClientesRecurso(conexao);
dtsRecursoClienteTableAdapters.RECURSO_CLIENTETabelaTableAdapter tabela = new dtsRecursoClienteTableAdapters.RECURSO_CLIENTETabelaTableAdapter();
for (int j = 0; j <= 10; j++) { // <- here
tabela.Insert(arr);
}
trx.Commit();
}
catch (SqlException ex)
{
try
{
trx.Rollback();
}
catch (Exception exRollback)
{
Response.Write(exRollback.Message);
}
}
}
功能excluirClientesRecurso
public void excluirClientesRecurso(SqlConnection conexao)
{
executaComando("TRUNCATE TABLE dbo.RECURSO_CLIENTE", conexao);
}
功能executaComando(----這裏出現錯誤----)
public void executaComando(string query, SqlConnection conexao)
{
try
{
SqlCommand cmd = new SqlCommand(query);
cmd.Connection = conexao;
cmd.ExecuteNonQuery();
conexao.Close();
}
catch (Exception ex)
{
throw ex;
}
}
順便說一句,你可能想看看在缺少'using'聲明(這可能導致連接耗盡),並在你的'executaComando'缺乏參數化(這表明來自其他領域的代碼可能會使用輸入的連接,這將非常糟糕 - 可能會導致sql注入等其他問題) –