我的连接数据库的类是同学给的,可是她这个类里没有连接数据库失败后的异常抛出,我想要让我的数据库连接失败的时候弹出"数据库连接失败!"这种字样.应该怎么修改我这个类?
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public class Conn
{
    
        private SqlConnection conn = null;
    
    private void Connect()
    {
                   conn = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=jcl;User ID=sa;Password=1234");
            conn.Open(); 
        
        
  
            
    }
    private void ColseConnect()
    {
        if (conn.State == ConnectionState.Open)
        {
            conn.Close();
            conn.Dispose();
        }
        
        
    }
    public SqlDataReader SelectData(string sql)
    {
        
            Connect();
            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlDataReader a = cmd.ExecuteReader();
            return a;
        
    }
    public bool ExcSql(string sql)
    {
        Connect();
        SqlCommand cmd = new SqlCommand(sql, conn);
        int rowffected = cmd.ExecuteNonQuery();
        return rowffected == 1;    }   
}

解决方案 »

  1.   

    try{}catch( exception ){ ...}
      

  2.   

    用trycatch。finally抛出异常。
    比如
    try
    {
       conn = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=jcl;User ID=sa;Password=1234");
        if( if (conn.State == ConnectionState.Close))
        { 
              conn.Open(); 
        }
    }
    catch()
    {
        //你的异常处理信息
    }
    finally
    {
      
    }
      

  3.   

    Data Source=.\\SQLEXPRESS;Initial Catalog=jcl;User ID=sa;Password=1234"
    这些连接信息可用吗?
      

  4.   

    不行,我添加进去后,登录页面输入帐号和密码后,还是出错
      public SqlDataReader SelectData(string sql)
        {
            
                Connect();
                SqlCommand cmd = new SqlCommand(sql, conn);
                SqlDataReader a = cmd.ExecuteReader();  
    提示户用代码未处理 InvalidOperationException
    ExecuteReader 要求已打开且可用的连接。连接的当前状态为已关闭 

                return a;
            
        }
      

  5.   

     public SqlDataReader SelectData(string sql)
        {
            
                Connect();
                SqlCommand cmd = new SqlCommand(sql, conn);
    这里提示错误
                SqlDataReader a = cmd.ExecuteReader();  
    提示户用代码未处理 InvalidOperationException
    ExecuteReader 要求已打开且可用的连接。连接的当前状态为已关闭 

                return a;
            
        }
      

  6.   

    可以用的,我这个是正确连接到我的数据库的.
    我在调用的时候都没问题,可是我们老师说要是把数据库删了,我前台使用的时候没有提示错误的,就不行><
      

  7.   

    conn = new SqlConnection("server=.;integrated security=true;database=jcl;");
      

  8.   

    SqlCommand cmd = new SqlCommand(sql, conn);
    下面加一句cmd.Connection.Open();
      

  9.   

    你直接在 连接语句那加一个 try{}catch{} 不就行了吗额