我已经尝试连接asp.net Webform aspx.vb和sql server,但问题是当我在Dim cn As New SqlConnection(con)
上写这段代码con
时出错了,我试着找出来为什么它不起作用。
错误讯息
con is not declared it may inaccessible sue to its protection level
我的Web.config代码
<connectionStrings>
<add name="connection"
connectionString="Data Source=HOUCHANDARA;Initial Catalog=website;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
我的模块代码
Imports System.Configuration
Public Module Connection
Public con As String = ConfigurationManager.ConnectionStrings("connection").ConnectionString
End Module
我的aspx.vb代码
Imports System.Data.SqlClient
Public Class HomePage
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim cn As New SqlConnection(con)
If Not IsPostBack Then
Try
cn.Open()
MsgBox("connect")
Catch ex As Exception
MsgBox("faild")
End Try
End If
End Sub
End Class
答案 0 :(得分:3)
使用
Dim cn As New SqlConnection(Connection.con)
除此之外,请注意ConfigurationManager.ConnectionStrings
也被缓存。因此,使用“全局”变量没有性能提升。您还应该使用Using
- 语句进行连接,以确保即使出错也会尽快处理/关闭。