简体   繁体   中英

I can't connect asp.net VB with SQL Server

I've been tried to connect asp.net Webform aspx.vb whith sql server,but problem is when I wrote this code Dim cn As New SqlConnection(con) it error on con , I try to find out why it doesn't work.

Error Message con is not declared it may inaccessible sue to its protection level

My Web.config code

<connectionStrings>
  <add name="connection"
  connectionString="Data Source=HOUCHANDARA;Initial Catalog=website;Integrated Security=True"
  providerName="System.Data.SqlClient" />
</connectionStrings>

My Module code

Imports System.Configuration

Public Module Connection
  Public con As String =  ConfigurationManager.ConnectionStrings("connection").ConnectionString
End Module

My aspx.vb code

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

Use

Dim cn As New SqlConnection(Connection.con)

apart from that, note that ConfigurationManager.ConnectionStrings is also cached. So there is no performance gain in using that "global" variable. You should also use the Using -statement for the connection to ensure that it gets disposed/closed as soon as possible even on error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM