"using" 后 ConnectionString 属性 尚未初始化
The ConnectionString property has not been initialized after "using"
我的连接字符串、我的数据库和一切都工作正常,但只是在我的页面上调用它一次。
我有几种方法可以连接到我的数据库,return 对我来说很有价值,而且我第一次需要使用其中的两种方法。我在 conn.Open()
:
中收到此错误
"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 属性 尚未初始化。
当我只调用一个时,效果很好。
我的这两种方法的来源是,我对每个人都使用几乎相同的代码,只是更改 table 名称:
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,但这也工作正常)
更改using语句如下。有关更多连接字符串,请参阅 this。
using (SqlConnection conn = new SqlConnection("Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"))
问题是 using
语句在 returns 时关闭了连接。
在您的 using 语句中创建 SqlConnection
,如下所示:
using (SqlConnection conn = new SqlConnection(connString)) { ... }
从您的配置文件获取连接字符串:
connString = ConfigurationManager.ConnectionStrings["yourConnString"].ConnectionString;
配置文件:
<connectionStrings>
<add name="yourConnString" connectionString="..." providerName="..."/>
</connectionStrings>
我的连接字符串、我的数据库和一切都工作正常,但只是在我的页面上调用它一次。
我有几种方法可以连接到我的数据库,return 对我来说很有价值,而且我第一次需要使用其中的两种方法。我在 conn.Open()
:
"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 属性 尚未初始化。
当我只调用一个时,效果很好。
我的这两种方法的来源是,我对每个人都使用几乎相同的代码,只是更改 table 名称:
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,但这也工作正常)
更改using语句如下。有关更多连接字符串,请参阅 this。
using (SqlConnection conn = new SqlConnection("Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"))
问题是 using
语句在 returns 时关闭了连接。
在您的 using 语句中创建 SqlConnection
,如下所示:
using (SqlConnection conn = new SqlConnection(connString)) { ... }
从您的配置文件获取连接字符串:
connString = ConfigurationManager.ConnectionStrings["yourConnString"].ConnectionString;
配置文件:
<connectionStrings>
<add name="yourConnString" connectionString="..." providerName="..."/>
</connectionStrings>