我收到一個錯誤如下:VB鏈接SQL服務器的問題
從類型轉換「的SqlConnection爲鍵入「串」是無效的。
我的VB編碼是:
Dim conn As New SqlConnection
Dim cmd As New SqlCommand
Dim da As New SqlDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Try
conn = New SqlConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT * FROM HostTable"
If Me.cboSearchBy.Text = "Name" Then
sSQL = sSQL & " where HOSTNAME like '%" & Me.txtSearch.Text & "%'"
ElseIf Me.cboSearchBy.Text = "Function" Then
sSQL = sSQL & " where FUCTION like '%" & Me.txtSearch.Text & "%'"
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
If dt.Rows.Count = 0 Then
MsgBox("No record found!")
End If
Function Get_Constring()
If Microsoft.VisualBasic.Right(Application.StartupPath, 1) = "\" Then
sConnstring = New SqlConnection("server=192.168.1.111\SQLSERVER;database=Common_DB;User ID=sa;Password=12345678")
Else
sConnstring = New SqlConnection("server=192.168.1.111\SQLSERVER;database=Common_DB;User ID=sa;Password=12345678")
End If
Return sConnstring
End Function
另外,考慮轉入Option Strict - 強烈鍵入您的返回並顯式聲明變量。或者使用'Return'server = 192.168.1.111 \ SQLSERVER; database = Common_DB; User ID = sa; Password = 12345678「'完全免除變量。 –