我是一名新開發人員。通過asp.net從多個網頁訪問SQL Server數據庫
我有一個網站需要訪問一個用戶帳戶,並通過不同的網頁像一個頁面查看他的個人資料數據在該數據庫中檢索他的所有信息的問題;另一個頁面查看他已經創建的檢查...等
我所做的是爲每個單獨的aspx頁面我必須創建一個新的對象,並從該對象連接到SQL Server數據庫,我覺得有東西那是錯的。
問題是,有什麼辦法可以只定義一次數據庫對象並使其可以從同一網站中的不同網頁進行訪問,並從該對象執行SQL查詢並檢索數據?
感謝
我是一名新開發人員。通過asp.net從多個網頁訪問SQL Server數據庫
我有一個網站需要訪問一個用戶帳戶,並通過不同的網頁像一個頁面查看他的個人資料數據在該數據庫中檢索他的所有信息的問題;另一個頁面查看他已經創建的檢查...等
我所做的是爲每個單獨的aspx頁面我必須創建一個新的對象,並從該對象連接到SQL Server數據庫,我覺得有東西那是錯的。
問題是,有什麼辦法可以只定義一次數據庫對象並使其可以從同一網站中的不同網頁進行訪問,並從該對象執行SQL查詢並檢索數據?
感謝
我們用這個實現使用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
這就是我一直在尋找的!非常感謝! – 2014-10-28 17:55:23
不錯。你能把它標記爲答案嗎? – 2014-10-28 19:27:35
您可以定義在web.config文件中的連接設置和訪問相同的your.aspx頁。 參考http://www.connectionstrings.com/store-connection-string-in-webconfig/
看ORM和Repository模式。 – 2014-10-26 14:17:59