使用asp.net调用存储过程

10
如果我在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 Server。

这就是我在寻找的内容:

ConnectionStringSettings conSet = ConfigurationManager.ConnectionStrings["db.Name"];
SqlConnection con = new SqlConnection(conSet.ConnectionString);

获取数据的代码相当简单。我更感兴趣的是如何从web.config文件中的connectionString变量访问它。


1
你是在使用VB.NET还是C#?(只是为了帮助你处理语法)。 - JonH
2个回答

8

如果它是一个资源文件,就像这样:

private static readonly string connString = Resource1.connString;

其中connString是密钥的名称。 如果它是web.config文件,则如下:

类似于:

private static readonly string connString = System.Configuration.ConfigurationManager.AppSettings["strConn"];其中conn在您的web config文件中定义。

<add key="strConn" value="User ID=test;Password=test;Initial Catalog=TestDB;Data Source=NameOfServer;"/>

然后调用存储过程:

  //connString = the string of our database app found in the resource file
                using (SqlConnection con = new SqlConnection(connString))
                {
                    using (SqlCommand cmd = new SqlCommand("EMPDLL_selClientByClientID", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add("@ClientID", SqlDbType.VarChar).Value = cID;
                        con.Open();

                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            if (reader.HasRows)
                            {
                                if (reader.Read())
                                {
                                       //more code
                                }
                             }
                        }
                     }
                  }

如果你在编写C#或VB.net代码,那么情况是一样的,只是需要多些字,以下是一个小示例:

 Public Sub DeleteEmployee(ByVal lVID As Long)
        Dim conMyData As SqlConnection
        Dim cmdDelete As SqlCommand

        Try
            conMyData = New SqlConnection(connString)
            cmdDelete = New SqlCommand("delEmployee", conMyData)

            With cmdDelete
                .CommandType = CommandType.StoredProcedure
                'add the parameters
                .Parameters.Add("@LoginID", SqlDbType.BigInt).Value = lVID    'the request
                conMyData.Open()    'open a connection
                .ExecuteNonQuery()  'execute it
            End With

        Catch ex As Exception
            Throw ex
        Finally
            cmdDelete = Nothing
            conMyData.Close()
            conMyData = Nothing
        End Try
    End Sub

当然,您应该使用using语句而不是try/catch/finally语句来确保清除正在使用的资源。

我不想在我的web.config中添加一个键(否则我必须编辑多个web.config文件)或将其输入为静态变量。如果我的连接字符串像我的帖子中定义的那样在我的web.config中定义,是否可以访问它? - onit
@Web.config文件中的@onit。 - JonH
@onit - 如果你只想要那个特定的部分,你可以使用 _SQLDBConnString = System.Configuration.ConfigurationManager.ConnectionStrings(1).ConnectionString() 并使用 ConnectionStrings 属性而不是 appsettings 部分。 - JonH
@onit - 如果您不想使用应用程序设置,请使用连接字符串属性:string test = ConfigurationManager.ConnectionStrings [0].ConnectionString; - JonH
不太在乎分数,来这里是为了帮助。如果这不是你要找的,请重新表述你的问题并添加更多细节。一个糟糕的问题会得到一个糟糕/半糟糕的回答。你问怎样从 web config 文件获取连接字符串,我认为我给了你更多的东西。 - JonH
显示剩余3条评论

5

Something like this...

using (var con = new SqlConnection(_connectionString))
{
    using (var cmd = new SqlCommand(_storedProcedureName, con))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@pMyParamater", myParamaterValue);
        con.Open();

        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                 // do something with the row
            }
        }
    }
}

这其实都是很简单的东西,你应该能够从ADO.NET文档中找到所需的一切。

1
如果你知道类型,为什么要使用“var”? - JonH
我意识到这不是很复杂的东西。我只是想知道是否有人可以指点我正确的方向,因为我刚刚开始学习.NET编程。 - onit
3
@onit 是的,我意识到了,那并不是批评。如果你对某个东西不熟悉,最好的习惯是首先阅读文档,然后如果还遇到问题在SO上提出更具体的问题。通过这种方式,你会学到更多,并且避免了有时在该网站上给出的错误建议。 - fearofawhackplanet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接