VB link SQL server problems - vb.net

I received a error as following:
Conversion from type 'SqlConnection' to type 'String' is not valid.
My VB coding is :
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

The parameter you have hardcoded inside New SqlConnection is the actual Connection String.
You may want to write something like:
sConnstring = "server=192.168.1.111\SQLSERVER;database=Common_DB;User ID=sa;Password=12345678"
myConnection = New SqlConnection(sConnstring)
So your function Get_Constring should just return the string, not an entire connection.
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
This should work as intended.

Conversion from type 'SqlConnection' to type 'String' is not valid.
This error message is very clear. You cannot convert a (new) SqlConnection to a string (sConnstring).

Related

VB.Net - ExecuteReader: CommandText property has not been initialized

I know there are some threads about this topic, but for some reason nothing of these things given there didn't work for me. So that is my code:
Dim strAccSQL As String = "SELECT nUserNo FROM dbo.tUser WHERE sUserID='" & AccountID.Text & "';"
Dim catCMDAcc As SqlCommand = New SqlCommand(strAccSQL, AccCon)
Dim myAccountReader As SqlDataReader = catCMDAcc.ExecuteReader()
While myAccountReader.Read
AccountNo.Text = myAccountReader(0)
End While
myAccountReader.Close()
Con.Close()
Con.Open()
Dim strSQL2 As String
Dim catCMD As SqlCommand = New SqlCommand(strSQL2, Con)
Dim myReader As SqlDataReader = catCMD.ExecuteReader()
InfoTextBox.Text &= Environment.NewLine & Now & " Account: " & AccountID.Text & " Found"
CharacterName.Properties.Items.Clear()
While myReader.Read()
CharacterName.Properties.Items.Add(myReader(0))
End While
myReader.Close()
AccCon.Close()
Con.Close()
Anyone got an idea for my problem?
As the errormessage states, your CommandText is empty string here (strSQL2):
Dim strSQL2 As String
Dim catCMD As SqlCommand = New SqlCommand(strSQL2, Con)
Dim myReader As SqlDataReader = catCMD.ExecuteReader()
You cannot execute an empty sql-clause.

Search between two dates in access database using sql

This is my code for search in access database 2010. My problem is that when I search between two datetimepicker the result is wrong in datagridview, I mean when I search from specific records between May and June it shows me records also from February.
Private Sub Search_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Dim bookdetials As New frmContactDetails
Try
'get connection string declared in the Module1.vb and assing it to conn variable
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT contact_id, first_name , birth_date, book_num, send_from, no_answer, no_answer_by, rec, book_answer_name, book_answer_num, send_date, send_to, project_name FROM tblAddressBook"
If CheckBox1.Checked = True Then
sSQL = sSQL & " where project_name like '%" & Me.TextBox2.Text & "%' " & _
" AND birth_date between '" & DateTimePicker1.Text & "' AND '" & DateTimePicker2.Text & "'"
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
Label4.Text = dt.Rows.Count
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
datepicker text should be converted to datetime format in sql
I had the same problem, the solution was too silly but it worked
use text instead of datetime in the db
make sure the datetimepicker enters "short format" data

Syntax error (comma) in query expression, header with commas

I am trying to check if value from label1 exist in dbf file column named : "NALOG,C,8". Header in DBF file I can not change, 'cause it represents column's format and field size. But with that I get this error : "Syntax error (comma) in query expression "NALOG,C,8 = #NAL"
Here is complete code :
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim FilePath As String = "C:\"
Dim DBF_File As String = "PROMGL"
Dim ColName As String = "NALOG,C,8"
'Dim SQLstr As String = "SELECT * FROM " & DBF_File
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV;User ID=Admin;Password="
'cmd = New OleDbCommand("SELECT * FROM " & DBF_File)
cmd = New OleDbCommand("SELECT * FROM PROMGL WHERE " & ColName & " = #NAL")
cmd.Connection = con
con.Open()
cmd.Parameters.AddWithValue("#NAL", Label1.Text)
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
con.Close()
Label6.Text = "EXIST" & TextBox1.Text
TextBox1.Text = ""
TextBox1.Focus()
Else
Label6.Text = "DOESN'T EXIST"
End If
end using
Thanks.
If you have a column that is named this:
Dim ColName As String = "NALOG,C,8"
Then I would change it too this:
Dim ColName As String = "[NALOG,C,8]"
Use this instead:
Dim ColName As String = "NALOG"

Check if value exist in DBF database

I am trying to check if value "IAV-1419" exist in second column (ColName) in database named PROMGL.DBF.
I get this error : No value give for one or more required parameters
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim FilePath As String = "C:\"
Dim DBF_File As String = "PROMGL"
Dim ColName As String = "[NALOG,C,8]"
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV"
cmd = New OleDbCommand("SELECT * FROM PROMGL WHERE [NALOG,C,8] = #NAL")
cmd.Connection = con
con.Open()
cmd.Parameters.AddWithValue("#NAL", "IAV-1419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
con.Close()
Label6.Text = "EXIST"
TextBox1.Text = ""
TextBox1.Focus()
Else
Label6.Text = "DOESN'T EXIST"
End If
End Using
I am stuck here, if anyone could please check this code for me.
are you sure that your connectionstring is correct????
Data Source=" & FilePath &
how connection string know the database where it point only to "C:\" i think is missing database name
Another personal suggestion make your code more simple to read in example :
Dim FilePath As String = "C:\"
Dim DBF_File As String = "PROMGL"
Dim ColName As String = "[NALOG,C,8]"
Using con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV")
con.Open()
Using cmd As New OleDbCommand("SELECT * FROM PROMGL WHERE [NALOG,C,8] = #NAL", con
cmd.Parameters.AddWithValue("#NAL", "IAV-1419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
Label6.Text = "EXIST"
TextBox1.Text = ""
TextBox1.Focus()
Else
Label6.Text = "DOESN'T EXIST"
End If
End Using
End Using
End Using

How do I return a list of integers using a VB.NET function?

I am working on a report in SSRS2005 where I need to use some VB.NET code to go out to a different database than the one in the report and return a list of integers (user IDs). I need to use some VB.NET code to do this. I have some code that 'works' in the sense that it does not throw any errors and I get values returned. However, I only get the first value and not the entire list. Here is what I have so far:
Public Function GetUsers(ByVal param As Integer) As String
Dim sqlCon As New System.Data.SqlClient.SqlConnection
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim dRet As String
Dim sCmdText As String
sqlCon.ConnectionString = "data source=myServer;initial catalog=myDatabase;Integrated Security=true"
cmd = New System.Data.SqlClient.SqlCommand
sCmdText = "SELECT UsersRowID FROM dbo.tvf_Get_Users("
'cmd.CommandType = CommandType.Text
cmd.Connection = sqlCon
cmd.CommandTimeout = 0
sCmdText = sCmdText & param
sCmdText = sCmdText & ")"
cmd.CommandText = sCmdText
If sqlCon.State <> System.Data.ConnectionState.Open Then
sqlCon.Open()
End If
dRet = cmd.ExecuteScalar() & ""
sqlCon.Close()
Return dRet
End Function
I have tried experimenting with using the DataSet data type but I get error messages that I cannot cast DataSet as a String.
Any ideas what I need to do to get this to work?
modify your code to the following
Public Function GetUsers(ByVal param As Integer) As String
'
Dim sqlCon As New System.Data.SqlClient.SqlConnection
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim dtAdapter As Data.SqlClient.SqlDataReader
Dim dRet As String
Dim sCmdText As String
'
'connection
sqlCon.ConnectionString = "data source=myServer;initial catalog=myDatabase;Integrated Security=true"
sqlCon.Open()
'
'query
sCmdText = "SELECT UsersRowID FROM dbo.tvf_Get_Users(" & param & ")"
'
'command
cmd = New System.Data.SqlClient.SqlCommand(sCmdText, sqlCon)
cmd.CommandTimeout = 0
'
'main course
If cmd.Connection.State = Data.ConnectionState.Closed Then cmd.Connection.Open()
dtAdapter = cmd.ExecuteReader(Data.CommandBehavior.CloseConnection)
If dtAdapter.HasRows Then
While dtAdapter.Read()
' following assumes "dbUserId" is the userid field in the database
' also use pipe "|" to split the userid's whens theres more than one
' this is so you can still use STRING as the function return and not an ARRAY
dRet = dRet & dtAdapter.GetValue(dtAdapter.GetOrdinal("dbUserId")) & "|"
End While
End If
If cmd.Connection.State <> Data.ConnectionState.Closed Then cmd.Connection.Close()
Return dRet
'
End Function