我收到如下错误:
从类型' SqlConnection'转换输入' String'无效。
我的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
答案 0 :(得分:1)
您在New SqlConnection
内硬编码的参数是实际的连接字符串。
你可能想要写一些类似的东西:
sConnstring = "server=192.168.1.111\SQLSERVER;database=Common_DB;User ID=sa;Password=12345678"
myConnection = New SqlConnection(sConnstring)
所以你的函数Get_Constring
应该只返回字符串,而不是整个连接。
Function Get_Constring()
If Microsoft.VisualBasic.Right(Application.StartupPath, 1) = "\" Then
sConnstring = "server=192.168.1.111\SQLSERVER;database=Common_DB;User ID=sa;Password=12345678"
Else
sConnstring = "server=192.168.1.111\SQLSERVER;database=Common_DB;User ID=sa;Password=12345678"
End If
Return sConnstring
这应该按预期工作。
答案 1 :(得分:0)
从“SqlConnection”类型到“String”类型的转换无效。
此错误消息非常清楚。您不能将(新)SqlConnection转换为字符串(sConnstring)。