2015-02-11 106 views
0

我一直试图连接asp.net Webform aspx.vb与SQL服务器,但问题是当我写这个代码Dim cn As New SqlConnection(con)它错误con,我尝试找出为什么它不起作用。我无法连接asp.net VB与SQL Server

错误消息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 
+1

包含您在con上收到的错误消息。 – 2015-02-11 15:11:01

+0

一旦你弄清楚了如何打开你的连接,你需要在代码中添加一个FINALLY块来关闭和销毁连接对象,以便将连接释放回池中。 – 2015-02-11 15:12:45

+0

而错误是?捕获异常而不显示错误消息有点无用。另外,请记住,当您在IIS上下文中运行此代码时,当前用户是用于启动IIS服务的用户。它需要有权限来打开Sql Server – Steve 2015-02-11 15:12:56

回答

3

使用

Dim cn As New SqlConnection(Connection.con) 

除此之外,注意ConfigurationManager.ConnectionStrings也被缓存。所以使用这个“全局”变量没有性能收益。您还应该使用Using -statement进行连接,以确保即使发生错误,它也会尽快处置/关闭。