Selecting an integer from an Access Database using SQL - sql

Trying to select an integer from an Access Database using an SQL statement in VB
Dim cmdAutoTypes As New OleDbCommand
Dim AutoTypesReader As OleDbDataReader
cmdAutoTypes.CommandText = "SELECT * FROM AutoTypes WHERE TypeId = '" & cboTypeIds.Text & "'"
AutoTypesReader = cmdAutoTypes.ExecuteReader
Error message says: "OleDbException was unhandled: Data type mismatch in criteria expression." and points to the AutoTypesReader = cmdAutoTypes.ExecuteReader line

Rather make use of OleDbParameter Class
This will also avoid Sql Injection.

You don't need the quotes in the query string. You're searching for a number, not a string.
cmdAutoTypes.CommandText = "SELECT * FROM AutoTypes WHERE TypeId = " & cboTypeIds.Text

Hi In access SQL you can't use single quote around your Integer type.
so
command text will be.. "SELECT * FROM AutoTypes WHERE TypeId = " & cboTypeIds.Text & " and .... "

In Access SQL, don't quote numeric constants.
And test whether IsNull(cboTypeIds). You can't do what you were planning to do until a value has been chosen.

Do not use string concatenation when you build your SQL query, use parameters instead.
Dim cmd As OledbCommand = Nothing
Dim reader as OleDbDataReader = Nothing
Try
Dim query As String = "SELECT * FROM AutoTypes WHERE TypeId = #Id"
cmd = New OledbCommand(query, connection)
//adding parameter implicitly
cmd.Parameters.AddWithValue("#Id", cboTypeIds.Text)
reader = cmd.ExecuteReader()
Catch ex As Exception
Messagebox.Show(ex.Message, MsgBoxStyle.Critical)
End Try
You can also explicitly state the parameter data type.
cmd.Parameters.Add("#Id", OleDbType.Integer).Value = cboTypeIds.Text
Hope this helps.

Related

How to concatenate single quote in MySQL query with VB.NET parameter?

I am making a MySQL Select query using MySQLCommand object in VB.NET were I use parameters. I am facing an issue, in my where clause, I need to put the value for the criteria into single quote, I tried to use backslash ' (\') to escape the single quote, it does not work. I used double quotes as well, same issue. Can somebody help me? Is there something specific I need to do when using the MySQLCommand object in VB.NET with parameter and want my parameter value to be in single quote into a query?
Here is the Function in which I make the MySQL query:
Public Shared Function getGeographyUnits(critere As String, valeur As String) As List(Of geography_unit)
Dim conn As MySqlConnection = DBUtils.GetDBConnection()
Dim rdr As MySqlDataReader
conn.Open()
Dim cmd As MySqlCommand = New MySqlCommand("select ID,description from geography_unit where #critere = ''#valeur''", conn)
cmd.Parameters.AddWithValue("#critere", critere)
cmd.Parameters.AddWithValue("#valeur", valeur)
rdr = cmd.ExecuteReader()
Dim geography_units As New List(Of geography_unit)
While rdr.Read
Dim geography_unit As New geography_unit
Try
geography_unit.ID = CLng(rdr("Id"))
geography_unit.description = rdr("description")
Catch ex As Exception
End Try
geography_units.Add(geography_unit)
End While
rdr.Close()
conn.Close()
Return geography_units
End Function
Actually, I want the cmdText for my query to be something like this after rendering:
select ID,description from geography_unit where critere = 'valeur'
The issue comes mainly from the fact that I am using parameter, how can I solve it?
You need to fix your code with something like this. But please note a couple of things.
If the #valeur is enclosed in single quotes it is no more a parameter placeholder but a string constant and the parameter associated with the placeholder will not be used.
The connection should always enclosed in a using statement to avoid dangerous resources consuption on the server
If you want to have a variable list of field to which apply the valeur passed then you need to be absolutely sure that your user is not allowed to type the value for critere. You should provide some kind of control like combobox or dropdwonlist where the user could only choose between a prefixed set of values, then you can concatenate the critere variable to your sql command.
Public Shared Function getGeographyUnits(critere As String, valeur As String) As List(Of geography_unit)
Using conn As MySqlConnection = DBUtils.GetDBConnection()
Dim sqlText As String = "select ID,description from geography_unit"
conn.Open()
If Not String.IsNullOrEmpty(critere) Then
sqlText = sqlText & " where " & critere & " = #valeur"
End If
Dim cmd As MySqlCommand = New MySqlCommand(sqlText, conn)
cmd.Parameters.Add("#valeur", MySqlDbType.VarChar).Value = valeur
Using rdr As MySqlDataReader = cmd.ExecuteReader()
Dim geography_units As New List(Of geography_unit)
While rdr.Read
Dim geography_unit As New geography_unit
Try
geography_unit.ID = CLng(rdr("Id"))
geography_unit.description = rdr("description")
Catch ex As Exception
End Try
geography_units.Add(geography_unit)
End While
End Using
' rdr.Close() not needed when inside using
' conn.Close() not needed when inside using
Return geography_units
End Using
End Function
Also worth of note is the point in which I have used the Add method to add the parameter to the collection. The AddWithValue, while convenient, is the cause of a lot of bugs because it defines the type of the parameter looking at the argument received. This could end very badly when you pass dates or decimal numbers directly from a string.
Quite simply, as valeur is a string then your query needs to be as follows
"select ID,description from geography_unit where critere = '" & valeur & "'"
If valeur was numeric then the format should be as follows
"select ID,description from geography_unit where critere = " & valeur
Note the difference where single quotes are included within double quotes around the variable when it is a string.

Why does jgejala = drkonsultasi.item(0) evaluate to invalid operation?

I have this code:
comkonsultasi = New OleDbCommand("select count(idkonsultasi) from dkonsultasi where idgejala='" & idgejala & "'", conn)
drkonsultasi = comkonsultasi.ExecuteReader
jgejala = drkonsultasi.Item(0)
When it runs, I get this exception message on the last line:
InvalidOperationException was unhandled. No data exists for the row/column.
Can anyone can help to resolve this problem?
You have to Read() from the DataReader. It's also very bad to use string concatenation to put data into an SQL query like that. You must use query parameters instead:
Dim sql As String = "select count(idkonsultasi) from dkonsultasi where idgejala= ?"
Using conn As New OleDbConnection("connection string here"), _
comkonsultasi As New OleDbCommand(sql, conn)
'Use the actual type and length from the database for this line
comkonsultasi.Parameters.Add("idgejala", OleDbType.VarWChar, 50).Value = idgejala
conn.Open()
Using drkonsultasi As OleDbDataReader = comkonsultasi.ExecuteReader()
If drkonsultasi.Read() Then
jgejala = drkonsultasi.Item(0)
End Using
End Using
End Using

How to concat to access cell using vb.net

I want to concat(add to what already exist) to an access cell using the text from a vb.net textbox. I tried using UPDATE but I'm getting a syntax error. This is what I tried so far
Dim ds As New DataSet()
Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\equip_full.mdb;Jet OLEDB:Database Password=matt"
Dim db As String = "Update INTO Equipment set TypeItem = ISNULL(TypeItem, '') & #EquipmentItem WHERE EquipmentCat = #category"
Using cn As New OleDbConnection(ConnectionString)
Using cmd = New OleDbCommand(db, cn)
cn.Open()
cmd.Parameters.Add("#EquipmentItem", OleDbType.VarWChar).Value = Form4.TextBox1.Text & ";"
cmd.Parameters.Add("#category", OleDbType.VarWChar).Value = Me.item_text.Text
Using reader = cmd.ExecuteReader()
'some code...
End Using
End Using
End Using
The correct syntax for an Update query is
UPDATE tablename SET field=value, field1=value1,.... WHERE condition
Then you need to remove that INTO that is used in the INSERT queries
Dim db As String = "Update Equipment set TypeItem = .... " &
"WHERE EquipmentCat = #category"
After fixing this first syntax error, then you have another problem with ISNull
ISNull is a boolean expression that return true or false.
If you want to replace the null value with an empty string you need the help of the IIF function that you could use to test the return value of ISNull and prepare the base string to which you concatenate the #Equipment parameter.
Something like this
Dim db As String = "Update Equipment " & _
"set TypeItem = IIF(ISNULL(TypeItem),'', TypeItem) & #EquipmentItem " & _
"WHERE EquipmentCat = #category"

the user must match to the 3 fields

Dim elem As String
elem = "Grade School"
Dim v As Integer
v = 0
Dim con As New SqlConnection("SERVER=ANINGDZTS-PC;DATABASE=AEVS;Trusted_Connection = yes;")
Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM tbl_Voter WHERE Department, VotersID = '" & elem & "''" & txt_PwordElem.Text & "'AND Voted ='" & v & "'", con)
con.Open()
Dim sdr As SqlDataReader = cmd.ExecuteReader()
Try
If (sdr.Read() = False) Then
high()
Else
MessageBox.Show("WELCOME!")
elemBallot.Show()
Me.Hide()
End If
Catch EX As Exception
MsgBox(EX.Message)
End Try
End Sub
this code is not working, an error appear," An expression of non-boolean type specified in a context where a condition is expected, near ','."
Instead of trying to create your SQL query via concatenating strings, which is prone to errors, a much better way is to use parametrized query. Change your SqlCommand declaration to
Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM tbl_Voter WHERE Department = #Department AND VotersID = #VotersID AND Voted = #Voted", con)
cmd.Parameters.AddWithValue("#Department", elem)
cmd.Parameters.AddWithValue("#VotersID", txt_PwordElem.Text)
cmd.Parameters.AddWithValue("#Voted", v)
Bonus: Avoid SQL Injection
P.S. Please don't forget to close your Reader and Connection after the use.
P.P.S. If you simple need to make sure that specific row in table "tbl_Voter" exists or not based on your parameters (which is, judging by the code what you're doing) - using DataReader is overkill. Consider query like SELECT 1 FROM tbl_Voter ... and use of ExecuteScalar to check returned value for Nothing

OledbException Data type mismatch in criteria expression

I'm getting a OledbException Data type mismatch in the criteria expression, at ad.Fill(xDataset, "TblMaster").
I'm using an Access database and Telerik Reporting.
This is my code
Public Sub TanggalX()
conn.Open()
Dim str9 As String = "Select * From TblMaster Where Tanggal='" & Me.DateTimePicker1.Value.Date.ToString("yyyy/MM/dd")) & "'"
ad = New OleDb.OleDbDataAdapter(str9, conn)
xDataset.Clear()
ad.Fill(xDataset, "TblMaster")
obj_RepDoc = New Report1
obj_RepDoc.DataSource = (xDataset)
Me.ReportViewer1.Report = obj_RepDoc
Me.ReportViewer1.RefreshReport()
Me.Show()
conn.Close()
End Sub
Please help me this is my last problem for this project.
You should use # instead of ' for Date/Time fields.
Dim str9 As String = "SELECT * FROM TblMaster WHERE Tanggal=#" & Me.DateTimePicker1.Value.Date.ToString("yyyy/MM/dd")) & "#"
My guess is that TblMaster.Tangall is of type Date and you are specifying it as a string in the WHERE clause of your SQL select command.
Try the following:
using (OleDbCommand comm = new OleDbCommand())
{
var parameter =comm.Parameters.AddWithValue("#tangall", Me.DateTimePicker1.Value);
parameter.OleDbType = OleDbType.DBDate;
using (var ad = new OleDbDataAdapter(comm))
{
... //do your stuff here
}
}
I think InBetween is right. You can also convert the string to date inside the SQL statement instead of using parameters by replacing your SQL statement with this:
Dim str9 As String = "Select * From TblMaster Where Tanggal=CDate('" & Me.DateTimePicker1.Value.ToString() & "')"