“使用"后,尚未初始化ConnectionString属性. [英] The ConnectionString property has not been initialized after "using"

查看:130
本文介绍了“使用"后,尚未初始化ConnectionString属性.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的连接字符串,我的数据库以及所有内容都可以正常工作,但是当我在页面上一次调用它时.

My connection string, my database, and everything is working just fine, but just when I call it once at my page.

我有几种方法可以连接到我的数据库并向我返回一个值,这是我第一次需要使用其中的两个.我在conn.Open()中收到此错误:

I have several methods that make connection to my database and return a value to me, and for the first time i need to use two of then. And i'm getting this error in conn.Open():

"ConnectionString属性尚未初始化." 描述:在执行当前Web请求期间发生未处理的异常.请查看堆栈跟踪以获取有关该错误及其在代码中起源的详细信息."

"The ConnectionString property has not been initialized." "Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code."

异常详细信息:System.InvalidOperationException:ConnectionString属性尚未初始化.

Exception Details: System.InvalidOperationException: The ConnectionString property has not been initialized.

当我打电话时,只有一个工作得很好.

When i call just one is working great.

我从这两种方法中得到的是,我对每个人都使用几乎相同的代码,只是更改了表名:

My source of two of this methods is, i'm using almost the same code for everyone, just changing the table name:

public DataTable Category(){
        sda = new SqlDataAdapter("select * from tbl_category", conn);
        sda.Fill(dt);
        return dt;
}

public int CategoryLastId(){
    using (conn){
       conn.Open();
       sqlCommand = new SqlCommand("SELECT MAX(Id) AS LastID FROM tbl_category", conn);
       sqlCommand.ExecuteNonQuery();
       Int32 newId = (Int32)sqlCommand.ExecuteScalar();
       conn.Close();
       return Convert.ToInt32(newId);
   }
}

感觉像他们在发生冲突(也可以通过NHibernate调用.Get,但这也可以很好地工作)

feels like they are in conflict(also, calling on .Get with NHibernate, but this also is working fine)

推荐答案

问题是using语句返回时将关闭连接.

The problem is that the using statement is closing the connection when it returns.

在using语句内创建SqlConnection,如下所示:

Create the SqlConnection inside your using statement as follows:

  using (SqlConnection conn = new SqlConnection(connString)) { ... }

要从配置文件中获取连接字符串:

For getting the connection string from your config file:

  connString = ConfigurationManager.ConnectionStrings["yourConnString"].ConnectionString;

配置文件:

   <connectionStrings>
      <add name="yourConnString" connectionString="..." providerName="..."/>          
   </connectionStrings>

这篇关于“使用"后,尚未初始化ConnectionString属性.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆