2014-09-16 8 views
1

DB 연결 작업을 위해이 클래스를 만들었습니다. 응용 프로그램은 정상적으로 작동하지만 하루에 한두 번이 오류가 발생합니다.C#에서 SQL Server와의 연결에 무작위 오류가 발생했습니다.

잘못된 작업입니다. 연결이 완료되었습니다. 검색어 실행시 : (다른 검색어)

또는 다른 번으로이 오류가 발생했습니다.

값 제한 시간이 만료되었습니다. 작업이 완료되기 전에 시간 초과 기간이 만료되었거나 서버가 응답하지 않습니다. 이 오류는 서버 주체에 연결하는 동안 발생했습니다.

및 희귀 오류 :

서버에서 결과를 수신 할 때 전송 수준의 오류. (공급자 : 세션 공급자, 오류 :? 19 - 쿼리를 실행할 때 연결할 수 없습니다.)

스레드가 중단되었습니다. 쿼리를 실행할 때

ExecuteNonQuery에는 열려 있고 사용 가능한 연결이 필요합니다. 연결의 현재 상태가 닫힙니다. 쿼리를

내 DB 클래스를 실행할 때 (다시 시작) :

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Data.SqlClient; 
using System.Data; 
using System.Net.Mail; 
using System.Web; 
using System.IO; 

namespace BBDD 
{ 
    public class clsBBDD 
    { 
     private string strConexion; 
     private int intTransaciones; 
     private SqlTransaction Transaccion; 
     private SqlConnection Conexion; 

     public clsBBDD(string ParamConexion) 
     { 
      strConexion = ParamConexion; 
      intTransaciones = 0; 
     } 

     public int Execute(string Sql) 
     { 
      return ExecutePrivado(Sql); 
     } 

     public int Execute(string Sql, bool Force) 
     { 
      return ExecutePrivado(Sql, Force); 
     } 

     private int ExecutePrivado(string Sql,bool Force = false) 
     { 
      int result = 0; 
      SqlCommand sentencia; 
      try 
      { 
       if (!Force && !Sql.ToUpper().Contains("WHERE") && !Sql.ToUpper().Contains("INSERT")) 
       { 
        throw new Exception("Sentencia Update o Delete sin WHERE"); 
       } 
       if (intTransaciones > 0) 
       { 
        sentencia = new SqlCommand(Sql, Conexion, Transaccion); 
       } 
       else 
       { 
        abrirConexion(); 
        sentencia = new SqlCommand(Sql, Conexion); 
       } 
       sentencia.CommandTimeout = 0; 
       result = sentencia.ExecuteNonQuery(); 
       cerrarConexion(); 
      } 
      catch (Exception e) 
      { 
       SendMailError(Sql, e); 
       result = 0; 
      } 
      return result; 
     } 

     public bool AbrirTrans() 
     { 
      try 
      { 
       intTransaciones += 1; 
       if (intTransaciones == 1) 
       { 
        abrirConexion(); 
        Transaccion = Conexion.BeginTransaction(); 
       } 
      } 
      catch (Exception e) 
      { 
       SendMailError("Error al abrir transacción", e); 
       return false; 
      } 
      return true; 
     } 

     public bool CerrarTrans(bool CommitTrans) 
     { 
      try 
      { 
       intTransaciones -= 1; 
       if (intTransaciones == 0) 
       { 
        if (CommitTrans) 
        { 
         Transaccion.Commit(); 
        } 
        else 
        { 
         Transaccion.Rollback(); 
        } 
        cerrarConexion(); 
       } 
      } 
      catch (Exception e) 
      { 
       SendMailError("Error al cerrar transacción", e); 
       return false; 
      } 
      return true; 
     } 

     public object GetValue(string Sql) 
     { 
      object resultado = null; 
      try 
      { 
       SqlCommand sentencia = getCommand(Sql); 
       SqlDataReader reader = sentencia.ExecuteReader(); 

       while (reader.Read()) 
       { 
        resultado = reader[0]; 
       } 
       reader.Close(); 

       cerrarConexion(); 
      } 
      catch (Exception e) 
      { 
       SendMailError(Sql, e); 
       resultado = null; 
      } 
      return resultado; 
     } 

     public DataRow GetValuesInRow(string sql) 
     { 
      DataRowCollection dsr; 
      DataRow result; 
      try 
      { 

       dsr = GetDSr(sql); 
       if (dsr.Count > 0) 
       { 
        result = dsr[0]; 
       } 
       else 
       { 
        result = null; 
       } 
      } 
      catch (Exception e) 
      { 
       SendMailError(sql,e); 
       result = null; 
      } 
      return result; 
     } 

     public DataSet GetDS(string Sql) 
     { 
      DataSet result = new DataSet(); 
      SqlDataAdapter adapter; 
      try 
      { 
       SqlCommand command = getCommand(Sql); 
       adapter = new SqlDataAdapter(command); 
       adapter.Fill(result); 
       cerrarConexion(); 
      } 
      catch (Exception e) 
      { 
       SendMailError(Sql, e); 
       result = null; 
      } 
      return result; 
     } 

     public DataRowCollection GetDSr(string sql) 
     { 
      DataRowCollection result; 
      try 
      { 
       DataSet ds = GetDS(sql); 
       result = ds.Tables[0].Rows; 
      } 
      catch (Exception e) 
      { 
       SendMailError(sql, e); 
       result = null; 
      } 
      return result; 
     } 

     private void abrirConexion() 
     { 
      Conexion = new SqlConnection(strConexion); 
      if (Conexion.State == ConnectionState.Closed) 
      { 
       Conexion.Open(); 
      } 
     } 

     private void cerrarConexion(bool Force = false) 
     { 
      try 
      { 
       if (intTransaciones == 0 && Conexion != null) 
       { 
        Conexion.Close(); 
       } 
      } 
      catch 
      { 
      } 
     } 

     private SqlCommand getCommand(string Sql) 
     { 
      SqlCommand result; 
      if (intTransaciones == 0) 
      { 
       abrirConexion(); 
      } 
      result = Conexion.CreateCommand(); 
      if (intTransaciones > 0) 
      { 
       result.Transaction = Transaccion; 
      } 
      result.CommandText = Sql; 
      result.CommandTimeout = 0; 
      return result; 
     } 

    } 
} 

내가 초기화 방법 클래스 :

public partial class frmBase : System.Web.UI.Page 
{ 
    protected clsBBDD BD; 
    protected void Page_Init(object sender, EventArgs e) 
    { 
     BD = new clsBBDD(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); 
     clsBase.BD = BD; 
    } 
} 

내 모든 웹 양식의 frmBase에서 유산과 clsBase

에서 heritatge 모든 clases를 들어

BD를 사용하려면 다음과 같이 호출하십시오.

string sql; 
DataRowCollection DSTrabajos; 
sql = "UPDATE tabletest SET validacion = '" + ValidacionText + "', ModificadoPor = '" + Username + "' WHERE referencia = " + ReferenciaID; 
BD.Execute(sql); 
sql = "SELECT orderID FROM TrabajosINBOX where referencia = " + ReferenciaID; 

DSTrabajos = BD.GetDSr(sql); 

foreach (DataRow r in DSTrabajos) 
{ 
    //more code inside 
} 
나는 다음 오류가

사라 내 클래스의 모든하는 SqlCommand의 CommandTimeout이 = 0을 추가 할 때210

내 연결 문자열

Data Source=ServerIP;Initial Catalog=BBDDNAME;User ID=USER;Password=***********;Max Pool Size=500;MultipleActiveResultSets=true 
+1

gestionate의 의미는 무엇입니까? –

+1

이러한 오류의 대부분은 Sql 서버에 연결하는 데 간헐적으로 문제가 발생하는 것처럼 보입니다 (예 : 네트워킹 문제). –

+0

문제 같은 연결을 사용하여 두 가지 다른 쿼리를 실행하려고 시도하는 것처럼 들리 네 .. 연결 풀링을 사용하여 연결 풀링을 시도하십시오. 다른 언어보다 C#이 다릅니다. – MethodMan

답변

0

PARAMS "값 제한 시간이 만료되었습니다. 작업이 완료되기 전에 시간 초과 기간이 만료되었거나 서버가 응답하지 않습니다. .이 오류는 서버 교장에 연결하는 동안 "

을하지만 지금은 특별한이 한 곳에서 다른 오류를 계속 :

"발생한 연결이 완료, 작동 불가. (다른 쿼리) "