为连接字符串创建单独的类

时间:2014-07-02 07:38:18

标签: c# winforms

我正在尝试为名为Connection.cs的连接创建单独的类,为什么我在执行查询时出现此错误

ExecuteNonQuery requires an open and available Connection. The connection's current state is closed

我做错了什么?

在我的Dal.cs课程中

 public void Insert(string f1,string f2)
            {
                string query;
                Connection c = new Connection();
                c.OpenCnn();
                try  {
                    query = "inset into ..."
                    cmd = new SqlCommand(query, con);
                    cmd.ExecuteNonQuery();
                }

               catch (Exception ex){
                   throw ex;
                }

                finally {
                     c.CloseCnn();
                }
            }

和我的Connection.cs类

public class Connection

    {
        SqlCommand cmd = new SqlCommand();
        SqlConnection con = new SqlConnection();

        public void OpenCnn()
        {
       string cnnStr = ConfigurationManager.ConnectionStrings["myconnstrng"].ToString();
            con = new SqlConnection(cnnStr);
            con.Open();
        }

        public void CloseCnn()
        {

            con.Close();
        }
    }

2 个答案:

答案 0 :(得分:1)

目前,con字段为private,无法从Connection类外部访问。

您可以向连接类添加属性:

public SqlConnection Connection { get { return con; } }

然后通过您的实例访问它:

 Connection c = new Connection();
 c.OpenCnn();
 try 
 {
      query = "inset into ..."
      cmd = new SqlCommand(query, c.Connection);
      cmd.ExecuteNonQuery();
 }

顺便说一句,我不确定你在con方法Insert中引用了什么(可能是局部变量而不是con字段,因为否则它甚至不会编译)

答案 1 :(得分:0)

public class Connection
{       
    SqlConnection con;

    public SqlConnection Conn { get { return con; } }

    public void OpenCnn()
    {
        string cnnStr = ConfigurationManager.ConnectionStrings["myconnstrng"].ToString();
        con = new SqlConnection(cnnStr);
        con.Open();
    }

    public void CloseCnn()
    {
        con.Close();
    }
}

方法Insert

注意SqlCommand初始化和使用公共财产conn

public void Insert(string f1, string f2)
{
    string query;
    Connection c = new Connection();
    c.OpenCnn();
    try  
    {
        query = "insert into ..."
        SqlCommand cmd = new SqlCommand(query, c.Conn);
        cmd.ExecuteNonQuery();
    }
    catch (Exception ex){
               throw ex;
    }
    finally {
       c.CloseCnn();
    }
 }