【问题标题】:Accessing SQL Server database from multiple webpages through asp.net通过asp.net从多个网页访问SQL Server数据库
【发布时间】:2014-10-26 13:30:41
【问题描述】:

我是一名新开发者。

我在创建一个网站时遇到问题,该网站需要访问一个用户帐户并通过不同的网页(例如用于查看其个人资料数据的一个页面)检索该数据库中的所有信息;另一个页面来查看他已经创建的考试......等等。

我所做的是为每个单独的 aspx 页面创建一个新对象并从该对象连接到 SQL Server 数据库,我觉得这有问题。

问题是我可以只定义一次数据库对象,并使其可以从同一网站的不同网页访问,并从该对象执行 SQL 查询并检索数据吗?

谢谢

【问题讨论】:

  • 查看 ORM 和存储库模式。

标签: asp.net sql-server database vb.net


【解决方案1】:

我们使用 MVC 来使用这个实现...也许您可以根据自己的需要调整它:

clsConnectionManager

Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Data.SqlClient
Imports System.Web.Configuration
Imports System.Data

Public Class clsConnectionManager

Implements IDisposable
<ThreadStatic> _
Private Shared pSqlConnection As SqlConnection
Private Shared pConnectionString As String

Public Shared ReadOnly Property Connection() As SqlConnection
    Get
        If pSqlConnection Is Nothing Then
            pConnectionString = WebConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
            pSqlConnection = New SqlConnection(pConnectionString)
            pSqlConnection.Open()
        End If

        If pSqlConnection.State = ConnectionState.Closed Then
            pSqlConnection.Open()
        End If

        Return pSqlConnection
    End Get
End Property

Public Sub Dispose() Implements System.IDisposable.Dispose
    If pSqlConnection IsNot Nothing Then
        pSqlConnection.Close()
    End If
End Sub

End Class

Web.config

<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=localhost;Initial Catalog=yourDBName;User ID=YourDBUserName;Password=YourUserPassword" providerName="System.Data.SqlClient" />
</connectionStrings>

使用

在您的课程中,您可以执行以下操作:

Public Sub dbGetAll()
        Try
            Using New clsConnectionManager()

                Using lObjSQLCommand = New SqlClient.SqlCommand("StoredProcedureName", clsConnectionManager.Connection)
                    lObjSQLCommand.CommandType = CommandType.StoredProcedure
                    Using lObjSqlDataReader As SqlClient.SqlDataReader = lObjSQLCommand.ExecuteReader()
                        Do While lObjSqlDataReader.Read()
                            /*Read rows...*/
                        Loop
                    End Using
                End Using
            End Using
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

【讨论】:

  • 这真的是我一直在寻找的!非常感谢!
【解决方案2】:

您可以在 web.config 文件中定义连接设置并在 your.aspx 页面中访问相同的设置。 参考http://www.connectionstrings.com/store-connection-string-in-webconfig/

【讨论】:

    猜你喜欢
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    相关资源
    最近更新 更多