使用 asp.net 调用存储过程
如果我在 web.config 文件中定义了连接字符串,如何从 C# 代码创建到 SQL 数据库的连接(抱歉忘记指定),然后调用存储过程。然后我想最终以某种方式使用这些数据作为 GridView 的数据源。
以下是 web.config 中连接字符串的定义方式:
<connectionStrings>
<add name="db.Name" connectionString="Data Source=db;Initial Catalog=dbCat;User ID=userId;Password=userPass;" providerName="System.Data.SqlClient" />
</connectionStrings>
数据库服务器是 Microsoft SQL 服务器。
这就是我一直在寻找的内容:
ConnectionStringSettings conSet = ConfigurationManager.ConnectionStrings["db.Name"];
SqlConnection con = new SqlConnection(conSet.ConnectionString);
获取数据的代码相当简单。我更感兴趣的是从 web.config 文件中的 connectionString 变量访问它。
If I have a connection string defined in my web.config file, how do I create a connection to the SQL db from C# code (sorry forgot to specify) and then call a stored procedure. I would then like to eventually use this data in some way as my DataSource for a GridView.
Here is how the connection string is defined in the web.config:
<connectionStrings>
<add name="db.Name" connectionString="Data Source=db;Initial Catalog=dbCat;User ID=userId;Password=userPass;" providerName="System.Data.SqlClient" />
</connectionStrings>
The db server is a Microsoft SQL server.
Here is what I was looking for:
ConnectionStringSettings conSet = ConfigurationManager.ConnectionStrings["db.Name"];
SqlConnection con = new SqlConnection(conSet.ConnectionString);
The code to get the data is fairly trivial. I was more interested in accessing it from a connectionString variable in the web.config file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果它是一个资源文件,如下所示:
private static readonly string connString = Resource1.connString;
其中 connString 是键的名称。如果它是一个
web.config
文件,类似于:
private static readonly string connString = System.Configuration.ConfigurationManager.AppSettings["strConn"];
其中 conn 定义在你的网络配置文件。然后调用存储过程:
如果您使用 C# 和 VB.net 进行编码,则同样的情况,只是更加冗长一点:),这里有一个小示例:
当然,您应该使用
using
语句,而不是try/catch/finally
确保清理正在使用的资源。If it's a resource file like so:
private static readonly string connString = Resource1.connString;
Where connString is the name of the key. If it is a
web.config
fileSomething like so:
private static readonly string connString = System.Configuration.ConfigurationManager.AppSettings["strConn"];
where conn is defined in your web config file.Then call the sproc:
That's if you are coding in C#, VB.net its the same deal just a bit more wordier :), here's a small sample:
Of course you should use a
using
statement instead oftry/catch/finally
to ensure you clean up your resources that are being used.像这样的东西...
说实话,这都是非常简单的东西,您应该能够从 ADO.NET 文档
Something like this...
This is all pretty simple stuff to be honest, you should be able to find everything you need from the ADO.NET documentation