Syntax error in VB.NET application using SQL - sql

Hi I have been learning VB.NET for about a month now. I am stuck on something I get an error message saying
Syntax error in union query.
The code in question is this.
Private Sub Button5_Click_1(sender As Object, e As EventArgs) Handles Button5.Click
Dim Builder As New OleDb.OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = IO.Path.Combine(Application.StartupPath, "C:\Users\Nige\Documents\Visual Studio 2012\Projects\MS_Access_SimplePassword\bin\Debug\Database1.mdb"),
.PersistSecurityInfo = True
}
LoginForm.txtUserName.Text = LoginForm.txtUserName.Text
If LoginForm.txtUserName.Text <> "" Then
End If
'do what you want to do
lblName.Text = LoginForm.txtUserName.Text
If lblName.Text = LoginForm.txtUserName.Text Then
Builder.Add("Jet OLEDB:Database Password", "password")
Using con As New OleDb.OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDb.OleDbCommand With
{
.Connection = con,
.CommandText =
<SQL>
("SELECT * FROM tblContacts WHERE number" = '55')
Identifier,
UserName,
UserPassword,
UserTimer
FROM tblContacts
</SQL>.Value
}
con.Open()
Dim Reader As OleDb.OleDbDataReader = cmd.ExecuteReader
If Reader.HasRows Then
Reader.Read()
TextBox1.Text = Reader.GetInt32(0).ToString
TextBox2.Text = Reader.GetString(1)
TextBox3.Text = Reader.GetString(2)
TextBox4.Text = Reader.GetString(3)
End If
End Using
End Using
End If
End Sub
The code above was supposed to when I click button5 search my "ms access database" called "tblContacts" for a row that references the number "55"
If my code looks strange in places it because I am a still on a learning path :)
Cheers

I can see a couple of errors in your code above:
Dim Builder As New OleDb.OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = "C:\Users\Nige\Documents\Visual Studio 2012\Projects\MS_Access_SimplePassword\bin\Debug\Database1.mdb"),
.PersistSecurityInfo = True
}
That Path.Combine with two absolute filename is logically wrong, but, nevertheless it works because Path.Combine is able to recognize that the two strings passed are two full filename and thus doesn't try to create an impossible path, but return directly the second string.
From MSDN on Path.Combine
The combined paths. If one of the specified paths is a zero-length
string, this method returns the other path. If path2 contains an
absolute path, this method returns path2.
Then, looking at your query, it clearly an invalid text for a select and thus you get the Syntax Error.
This could be the correct way to query the datatable assuming
You search for a row with a column named 'number'
This column is of text type text
One or more rows contains in this column a text equals to '55'
Dim sqlText = "SELECT Identifier, UserName, UserPassword, UserTimer " +
"FROM tblContacts WHERE number = '55'";
Using con = New OleDb.OleDbConnection(Builder.ConnectionString)
Using cmd = New OleDb.OleDbCommand(sqlText, con)
con.Open()
Using Reader = cmd.ExecuteReader
While Reader.Read()
TextBox1.Text = Reader.GetInt32(0).ToString
TextBox2.Text = Reader.GetString(1)
TextBox3.Text = Reader.GetString(2)
TextBox4.Text = Reader.GetString(3)
End While
End Using
End Using
End Using

Related

Database query not returning results from value

I am making a work management system and I am fairly new to Visual Basic.
What I am trying to do is retrieve the name of the employee from the database with the given ID. After that I want this name to be displayed in a Label. After that, he can press the Work Start or Work end buttons.
Here is the code:
Private Function employeeSearchwithID(PersonalNr As String) As String
Dim mitarbeiter As String
Dim r As DataRow
Access.ExecQuery("SELECT [Vorname], [Name] from [TA-Personal] WHERE ([Personal_Nr] = '" & PersonalNr & "');")
'Report and Abort on Erros or no Records found
If NoErros(True) = False Or Access.RecordCount < 1 Then Exit Function
r = Access.DBDT.Rows(0)
'Populate Label with Data
mitarbeiter = r.Item("Vorname") & " " & r.Item("Name")
Return mitarbeiter
End Function
It is used like this:
Private Sub tbxUserInput_KeyDown(sender As Object, e As KeyEventArgs) Handles tbxUserInput.KeyDown
If e.KeyCode = Keys.Enter Then 'employeeIDnumbersSelect()
Label5.Text = employeeSearchwithID(tbxUserInput.ToString)
End If
End Sub
So, the plan is to have this program running on a tablet connected to a scanner. Every employee will have a personal card. When they scan the card, I want their names to be displayed. Of course, the card will be with the ID. But I am having trouble with the names: when I give my personal number it comes up as an empty string.
I have a separate DB Module. I learned from a tutorial:
Imports System.Data.OleDb
Public Class DBControl
' DB Connection
Public DBCon As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\recycle2000.mdb;")
'DB Command
Public DBCmd As OleDbCommand
'DB Data
Public DBDA As OleDbDataAdapter
Public DBDT As DataTable
'Public Myreader As OleDbDataReader = DBCmd.ExecuteReader
'Query Paramaters
Public Params As New List(Of OleDbParameter)
' Query Stats
Public RecordCount As Integer
Public Exception As String
Public Sub ExecQuery(Query As String)
'Reset Query Stats
RecordCount = 0
Exception = ""
Try
'Open a connection
DBCon.Open()
'Create DB Command
DBCmd = New OleDbCommand(Query, DBCon)
' Load params into DB Command
Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
' Clear params list
Params.Clear()
' Execute command & fill Datatable
DBDT = New DataTable
DBDA = New OleDbDataAdapter(DBCmd)
RecordCount = DBDA.Fill(DBDT)
Catch ex As Exception
Exception = ex.Message
End Try
' Close your connection
If DBCon.State = ConnectionState.Open Then DBCon.Close()
End Sub
' Include query & command params
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New OleDbParameter(Name, Value)
Params.Add(NewParam)
End Sub
End Class
Without knowledge of the Access class, I have to recommend a different approach to querying the database. It is important to make sure that the database is not vulnerable to SQL injection, be it deliberate or accidental. The way to do that is to use what are known as SQL parameters: instead of putting the value in the query string, the value is supplied separately.
Private Function EmployeeSearchwithID(personalNr As String) As String
Dim mitarbeiter As String = String.Empty
Dim sql = "SELECT [Vorname], [Name] from [TA-Personal] WHERE [Personal_Nr] = ?;"
Using conn As New OleDbConnection("your connection string"),
cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#PersonalNr",
.OleDbType = OleDbType.VarChar,
.Size = 12,
.Value = personalNr})
conn.Open()
Dim rdr = cmd.ExecuteReader()
If rdr.Read() Then
mitarbeiter = rdr.GetString(0) & " " & rdr.GetString(1)
End If
End Using
Return mitarbeiter
End Function
Private Sub tbxUserInput_KeyDown(sender As Object, e As KeyEventArgs) Handles tbxUserInput.KeyDown
If e.KeyCode = Keys.Enter Then 'employeeIDnumbersSelect()
Dim employeeName = EmployeeSearchwithID(tbxUserInput.Text.Trim())
If String.IsNullOrEmpty(employeeName) Then
MessageBox.Show("Not found.", "Problem", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
Label5.Text = employeeName
End If
End If
End Sub
The Using command makes sure that the "unmanaged resources" involved in querying a database are cleaned up afterwards, even if something goes wrong.
You will need to change the value of OleDbType.VarChar and .Size = 12 to match the type and size of that column in the database.
The name of the parameter is only for convenience with OleDb because it is ignored in the actual query, which uses "?" as a placeholder. Please see OleDbCommand.Parameters Property for full information.
If it still does not work, then please enter the ID manually in the tbxUserInput and see if you can make it work that way.
Hang on... tbxUserInput.ToString should be tbxUserInput.Text. But everything else I wrote still applies.

how to display data in text box in vb.net using sql

Private Sub BtnReturn_Click(sender As Object, e As EventArgs) Handles btnReturn.Click
If BorrowAccession.Text = "" Or txtBorrowerstype.Text = "" Then
MsgBox("All fields are required.", MsgBoxStyle.Exclamation)
ElseIf txtremarks.Text = "Over Due" Then
sql = "Select * From `maintenance` fine ='" & txtfine.Text & "' "
reloadtxt(sql)
End sub
how will i display the fine in txtfine.text from my maintenance database after it satisfy the condition from txtremarks. i tried some youtube tutorials but only displaying it from data grid .. want i basically want is directly display it from database to textbox. btw im newbie in vb programming thank you in advance
for my reloadtxt this is the code.
Public Sub reloadtxt(ByVal sql As String)
Try
con.Open()
With cmd
.Connection = con
.CommandText = sql
End With
dt = New DataTable
da = New MySqlDataAdapter(sql, con)
da.Fill(dt)
Catch ex As Exception
' MsgBox(ex.Message & "reloadtxt")
Finally
con.Close()
da.Dispose()
End Try
End Sub
To populate an object with data from a database you need to access the objects text property.
Textbox1.Text = "Some Text, static or dynamic"
Since you are pulling the data from a datatable you would access the column named "fine" and put that value in the textbox.text property.
Textbox1.Text = dt.row(0).item("fine").tostring
Changed Or to OrElse because it short circuits the If and doesn't have to check the second condition if the first condition is True.
In the reloadtxt method you filled a DataTable and did nothing with it. I changed it to a Function that returns the DataTable. The connection and command are now included in a Using...End Using block so they are closed and disposed even if there is an error.
Never concatenate strings to build an sql statement. Always used parameters.
Private Sub BtnReturn_Click(sender As Object, e As EventArgs) Handles btnReturn.Click
If BorrowAccession.Text = "" OrElse txtBorrowerstype.Text = "" Then
MsgBox("All fields are required.", MsgBoxStyle.Exclamation)
ElseIf txtremarks.Text = "Over Due" Then
Dim dt = reloadtxt()
DataGridView1.DataSource = dt
End If
End Sub
Public Function reloadtxt() As DataTable
Dim dt As New DataTable
Using con As New MySqlConnection("Your connection string"),
cmd As New MySqlCommand("Select * From maintenance Where fine = #Fine", con)
cmd.Parameters.Add(#Fine, MySqlDbType.VarChar, 50).Value = txtfine.Text
Try
con.Open()
dt.Load(cmd.ExecuteReader)
Catch ex As Exception
MsgBox(ex.Message & "reloadtxt")
End Try
End Using
Return dt
End Function

How do i make padleft work with the below code. I want to do search with out leading zero

With the below code I can pull info with zero in the front. I am trying to eliminate entering zero for instance 789136 for 0789136. Please advise
Private Sub BtnSearch_Click(sender As System.Object, e As System.EventArgs) Handles BtnSearch.Click
Dim connection As New SqlConnection("DATABASE CONNECTION")
Dim Table As New DataSet
Dim ZeroFill As String
If TxtBoxW1.Text = "" Then
ZeroFill = TxtBoxW1.Text.Trim
ZeroFill = ZeroFill.PadLeft(4, "0")
MsgBox(" Please Enter a valid number", MessageBoxButtons.OK)
TxtBoxW1.Focus()
connection.Open()
Else
adapter = New SqlDataAdapter("Select * From TABLENAME where COLNAME = '" & TxtBoxW1.Text.Trim & "'", connection)
Command = New SqlCommandBuilder(adapter)
ds1 = New DataSet()
adapter.Fill(ds1, "TABLENAME")
DataGridView1.DataSource = ds1.Tables("TABLENAME")
End If
connection.Close()
End Sub
your code does not make sense in many was. I'm not even sure what do you really need with those leading zeros.
1) Removing leading zeros
Dim Value As String = "0789136"
Dim ValueWithoutLeadingZeros As String = Value.TrimStart("0"c)
2) Other incinsistencies
Your if statement tests for empty string in TxtBoxW1. So there's no reason to read this
ZeroFill = TxtBoxW1.Text.Trim
ZeroFill = ZeroFill.PadLeft(4, "0")
since it will allways result in
ZeroFill = "0000"
and you're not using this value anyway.
Your connection.open and connection.close shoudl be all in the Else section, since you're not using it in if section. But this might be code cleanup consequence.
You should use parameters instead of direct query. Current version is risky for SQL Injection.
You shoudl use Using for Disposable objects.
3) Guessed version
I guess you want to trim leading zeros for validation, but pad your value with zeros for SQL search. In that case, your code should look somehow like this:
If TxtBoxW1.Text.Trim(" "c, "0"c).Length = 0 Then
MsgBox(" Please Enter a valid number", MessageBoxButtons.OK)
TxtBoxW1.Focus()
Else
Dim DS As New DataSet
Using Conn As New SqlConnection("DATABASE CONNECTION"), DA As New SqlDataAdapter("Select * From TABLENAME where COLNAME = #Param", Conn)
DA.SelectCommand.Parameters.Add(New SqlParameter("#Param", TxtBoxW1.Text.Trim.PadLeft(4, "0")))
Conn.Open()
DA.Fill(DS, "TABLENAME")
DataGridView1.DataSource = DS.Tables("TABLENAME")
End Using 'This will close the Connection for you
End If
My working code below:
Private Sub BtnSearch_Click(sender As System.Object, e As System.EventArgs) Handles BtnSearch.Click
SqlSelect = ""
sqlwhere = ""
expsql = sqlfrom & sqlwhere
Dim connection As New SqlConnection("database connection")
' Dim Command As New SqlCommand("Select * from table name where col1=#col1 = '" & TxtBoxW1.Text & "'", connection)
Dim Table As New DataSet
Dim sql As New SqlConnection
Dim ZeroFill As String
Dim ds as DataSet
connection.Open()
If TxtBoxW1.Text <> "" Then
ZeroFill = TxtBoxW1.Text.Trim
ZeroFill = ZeroFill.PadLeft(4, "0")
sqlwhere = ZeroFill
' MsgBox(" Please Enter a valid number", MessageBoxButtons.OK)
TxtBoxW1.Focus()
End If
adapter = New SqlDataAdapter("Select * From table name where col1 = " & sqlwhere & "", connection)
'adapter = New SqlDataAdapter(Sql, connection)
Command = New SqlCommandBuilder(adapter)
ds = New DataSet()
Try
adapter.Fill(ds, "Table Name")
DataGridView1.DataSource = ds1.Tables("Table Name")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
connection.Close()
End Sub

showing a sql coulmn data in a vb.net combobox

I want to show all the data in a specific column in one combobox and my code is just showing the last data in the column here is the code i am using
Dim connectionstring As String = "Data Source=localhost\SQLEXPRESS;InitialCatalog=Enginee;Integrated Security=True"
Try
Dim connection As New SqlClient.SqlConnection(ConnectionString)
Dim sqlquery As String
connection.Open()
MessageBox.Show("Open")
sqlquery = " Select PROJECT.PROJECT_CODE,PROJECT.PROJECT_NAME From PROJECT INNER JOIN ENGINEERS on ENGINEERS.ENGINEER_ID = ENGINEERS.ENGINEER_ID where ENGINEERS.FNAME = '" & Sign_In.TextBox1.Text & "' "
Dim selectcommand As New SqlClient.SqlCommand(sqlquery, connection)
Dim reader As SqlClient.SqlDataReader = selectcommand.ExecuteReader
Dim test As Boolean = reader.Read
While test = True
ComboBox1.Text = reader(0)
TextBox1.Text = reader(1)
test = reader.Read
End While
Catch ex As Exception
MessageBox.Show("Failed")
End Try
Instead of setting the .text of the ComboBox add the item.
ComboBox1.Items.Add(reader(0));
Setting the Text value will just set what the current item is, not adding them to the dropdown list.

InvalidCastException saying that "Specified cast is not valid."

Hi I got an InvalidCastException saying that "Specified cast is not valid.". I dont know where is the problem. Does my code has an error?
This is my code:
Private Sub Form5_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\patientinfo.accdb"
Conn.Open()
'====retrieve values in database=============
Dim statement As String = " SELECT patient_name,patient_age,date_confinement,type_sickness, type_fluid, bottle_used, drop_rate FROM tblPatientInfo WHERE 1 ORDER BY ID "
RetrieveInfos(statement)
End Sub
Public Sub RetrieveInfos(ByRef statement As String)
Dim cmd As OleDbCommand = New OleDbCommand
With cmd
.CommandText = statement
.CommandType = CommandType.Text
.Connection = Conn
.ExecuteNonQuery()
'--read records in access database----------------
Dim reader As OleDbDataReader = cmd.ExecuteReader
If reader.Read Then
lblName.Text = reader.GetString(0)
lblAge.Text = reader.GetString(1)
lblDate.Text = reader.GetString(2)
lblSickness.Text = reader.GetString(3)
lblFluid.Text = reader.GetString(4)
lblBottle.Text = reader.GetString(5)
lbldrops.Text = reader.GetString(6)
reader.Close()
End If
End With
End Sub
Any help would be appreciated. Thanks! :3
A very annoying part of VB working with datatypes is that some of them cause it to have a huge flap if they're empty. Best way around is to convert the ready to either an empty value or the default null value for the data type. Try the following:
lblName.Text = If(reader.isdbnull(0),Nothing,reader.GetString(0))
lblAge.Text = If(reader.isdbnull(1), 0, reader.GetInt16(1))
lblDate.Text = If(reader.isdbnull(2), date.minvalue, reader.Getdatetime(2)
lblSickness.Text = If(reader.isdbnull(3), Nothing, reader.GetString(3)
lblFluid.Text = If(reader.isdbnull(4), Nothing, reader.GetString(4))
lblBottle.Text = If(reader.isdbnull(5), Nothing, reader.GetString(5))
lbldrops.Text = If(reader.isdbnull(6), Nothing, reader.GetString(6))
Based on your comment to the question, I would suggest changing
lblAge.Text = reader.GetString(1)
to
lblAge.Text = reader.GetInt32(1).ToString
Also, make sure you use the appropriate Get for each column. For a Date you should use GetDateTime(). Here is a link to the MSDN for OleDbDataReader; the left side will have a list of all the methods that you can use for reference.
Try checking if the value is null:
If TypeOf reader(1) Is DBNull Then
lblAge.Text = reader.GetString(1)
End If
But that will only work if it's a string. If it's not a string, this should work with any data type:
If TypeOf reader(1) Is DBNull Then
lblAge.Text = reader(1).ToString()
End If