开发者

Connection to SQL Server not Working

I using vb.net 2010 and sql server management express 2008. bu I little confused what is wrong with the code for connect sql and vb.net

Imports System.Data.SqlClient

Module Module1
  Public Class connection
    Public Function GetConnect()
      Dim conn As SqlConnection = Nothin开发者_Python百科g
      Dim connString As String = "Data Source=.\SQLEXPRESS; Initial  Catalog=dbMedical;Integrated Security=true"
      conn = New SqlConnection(connString)
      conn.Open()
      If conn.State <> ConnectionState.Open Then
        Return False
      Else
        Return True
      End If
    End Function
  End Class
End Module

but but it does not work, error message appears.


You have an inner class inside of a Module, is that what you really wanted? Apart from that, you cannot open connections etc. outside of a method context and that is what you've made iny our connection-Class. Create a method that returns the connection.

For example:

Public NotInheritable Class DatabaseFactory

    Private Sub New()
    End Sub

    Public Shared Function GetConnection(openNow as Boolean) As SqlConnection
            Const connString = "Data Source=.\SQLEXPRESS; Initial Catalog=dbMedical;Integrated Security=true"
            Dim conn As SqlConnection = New SqlConnection(connString)
            If openNow Then conn.Open()
            Return conn 
    End Function
End Class


 Imports System.Data
 Imports System.Data.SqlClient      
 Module Connect  
 Public con As SqlConnection     
    Public Function GetConnect()
    con = New SqlConnection("Data Source='(LOCAL)';Initial Catalog='School';Database='School';User ID='sa';Password='';")
    Return con
    End Function
  End Module

After in form activated event:

con=GetConnect()
con.open()
-----
-----
con.close()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜