使用 asp.net 调用存储过程

发布于 2024-12-10 20:42:19 字数 701 浏览 0 评论 0原文

如果我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不再见 2024-12-17 20:42:19

如果它是一个资源文件,如下所示:

private static readonly string connString = Resource1.connString;

其中 connString 是键的名称。如果它是一个 web.config 文件

,类似于:

private static readonly string connString = System.Configuration.ConfigurationManager.AppSettings["strConn"]; 其中 conn 定义在你的网络配置文件。

<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 确保清理正在使用的资源。

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 file

Something like so:

private static readonly string connString = System.Configuration.ConfigurationManager.AppSettings["strConn"]; where conn is defined in your web config file.

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

Then call the sproc:

  //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
                                }
                             }
                        }
                     }
                  }

That's if you are coding in C#, VB.net its the same deal just a bit more wordier :), here's a small sample:

 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

Of course you should use a using statement instead of try/catch/finally to ensure you clean up your resources that are being used.

何以心动 2024-12-17 20:42:19

像这样的东西...

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 文档

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
            }
        }
    }
}

This is all pretty simple stuff to be honest, you should be able to find everything you need from the ADO.NET documentation

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文