[英]I am unable to connect my database in the connection string
I am a beginner in Visual Studio and in using SQL Server databases. 我是Visual Studio和使用SQL Server数据库的初学者。 I have connected my SQL Server database in Server Explorer and tested the connection;
我已经在服务器资源管理器中连接了我的SQL Server数据库并测试了连接; it connected successfully.
它成功连接。
Now I have a problem adding a row in the database using the Visual Studio coding. 现在我有一个问题,使用Visual Studio编码在数据库中添加一行。 I don't know how to connect to that SQL Server database using that connection string.
我不知道如何使用该连接字符串连接到该SQL Server数据库。 I am posting the images for the same.
我要发布相同的图像。 This is the image with the coding I had used, the Text line which is coloured is
这是我使用过编码的图像,彩色的文本行是
(
cnn.ConnectionString =
System.Configuration.ConfigurationManager.ConnectionStrings[
"Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-WebApplication5-20160919115911;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-WebApplication5-20160919115911.mdf "
].ConnectionString;
)
My web.config screen shot is like this. 我的web.config屏幕截图是这样的。
The text in the connection string is 连接字符串中的文本为
( <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-WebApplication5-20160919115911;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-WebApplication5-20160919115911.mdf" /> )
Please guide me what to do. 请指导我该怎么做。
I had made the database on localhost
. 我已经在
localhost
上建立了数据库。
您必须传递配置条目的名称(在本例中为DefaultConnection
才能从配置文件中获取它,而不是从连接字符串本身获取,因此正确的代码是这样
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"];
ConnectionStrings
takes the name
, not the entire string. ConnectionStrings
采用name
,而不是整个字符串。
So correct code is cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["name"];
因此正确的代码是
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["name"];
The connectionString must be include in appconfig or webconfig (config File)
connectionString必须包含在appconfig或webconfig中(配置文件)
Set ConnectionString 设置ConnectionString
<configuration>
<connectionStrings>
<add name="ConStr" connectionString="Data Source=.;Initial Catalog=balbla;IntegratedSecurity=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
GetConnectionString : GetConnectionString:
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.