我使用vb.net 2010和sql server management express 2008.我很困惑连接sql和vb.net的代码有什么问题
Imports System.Data.SqlClient
Module Module1
Public Class connection
Public Function GetConnect()
Dim conn As SqlConnection = Nothing
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
但是它不起作用,会出现错误消息。
答案 0 :(得分:0)
你有一个内部类的模块,这是你真正想要的吗?除此之外,您无法在方法上下文之外打开连接等,这就是您在connection
- 类中所做的。创建一个返回连接的方法。
例如:
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
答案 1 :(得分:0)
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
在表单激活事件之后:
con=GetConnect()
con.open()
-----
-----
con.close()