Can't compare vb.net item with access number - sql

Edit: For anyone facing this problem, don't miss the tips about only using
parameters instead of inserting the values directly into the SQL queries.
i'm facing a big problem with my vb.net project, i'm stuck with this for a week
i've a combobox item that i need to compare with an access number which is my database to retrieve some information, but i just got an error, no matter what format i convert my combobox item, it says my datatype is inconpatible with the expression
Here's one of the SQL queries from my code:
Dim dt1 As New DataTable
'This query select some itens from a row that match with the selected combobox number
Dim find1 As New OleDb.OleDbDataAdapter("SELECT Product, Number," _
& " Customer, Quantity, ProductionDate, AskDay, Pack, Company FROM RegOPE" _
& " WHERE Number ='" & CInt(mycombobox.SelectedItem) & "'", cn)
'Ive tried SelectedItem, Item, Text, SelectedValue...
'For conversion i tried parse, tryparse, conversion...
cn.Open() 'Opens database connection
find1.Fill(dt1) <- I got the error here
cn.Close() 'Close database connect
mydatagrid.DataSource = dt1 'Show the result in datagridview

number criteria should be without quote
Dim find1 As New OleDb.OleDbDataAdapter("SELECT Product, Number, " _
& "Customer, Quantity, ProductionDate, AskDay, Pack, Company FROM RegOPE " _
& "WHERE Number =" & CInt(mycombobox.SelectedItem), cn)
But better always use parameters:
Dim comm = New OleDb.OleDbCommand("SELECT Product, Number, " _
& "Customer, Quantity, ProductionDate, AskDay, Pack, Company FROM RegOPE " _
& "WHERE Number =?", cn)
comm.Parameters.AddWithValue("unusedName", mycombobox.SelectedItem)
Dim find1 As New OleDb.OleDbDataAdapter(comm)

In your WHERE clause have you tried to remove the quotes ? They are not required if you are looking for a number.

First, I must mention that you really ought to be using parameters. You should not concatenate the values directly into the SQL command string like that. Your SQL command string should simply contain parameter name placeholders for those values and then you should specify the values for those parameters separately.
However, if you are going to concatenate the value with the command like that, the command is a string, not an integer. It makes little sense to use CInt to convert the item to an integer just before concatenating it with a string (which requires first converting it from the integer into a string). It would make more sense to simply call ToString to convert it to a string, instead of CInt. Also, if the Number column in your database is typed as a number, rather than as text, then you should not be surrounding the value with quotes.
I recommend trying this:
Dim find1 As New OleDb.OleDbDataAdapter("SELECT Product, Number," _
& " Customer, Quantity, ProductionDate, AskDay, Pack, Company FROM RegOPE" _
& " WHERE Number =" & mycombobox.SelectedItem.ToString(), cn)
Although, recommend is to strong a word, since I would never recommend doing it that way in the first place. Use parameterized queries!

Related

Excel to VB: Can't read the zero behind

I'm doing a connection with excel and I have a problem when I try to use an ID that have 0 behind...
I'm using a ListBox and add the IDs from the excel's worksheet as items. IDs have 9 numbers, like "123456789" or "098765430". So that I remove the last 4 characters to search the IDs with the same 5 numbers and add in another ListBox. It works fine, except with the codes with 0 (zero) behind.
Dim ConnectionString As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Application.StartupPath & "\Tabela_Precos.xlsx; Extended Properties=Excel 12.0;")
ConnectionString.Open()
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da
For i = 0 To Form1.ListBox1.Items.Count - 1
Dim str As String = Compras.ListBox1.Items(i).ToString
Dim prod As String = str.Remove(str.Length - 4)
da = New OleDbDataAdapter("SELECT * FROM [Sheet1$] WHERE ID like '%" & prod & "%'", ConnectionString)
ListBox1.Items.Add(dt.Rows(i).Item(0))
Next
Your Excel file has the ID column entered as integer values, but is formatted for left-zero padding to present as a nine character field. Your Excel db connection is reading the values as numbers (type Double, even-though they are integers). Your original select statement is implicitly convert ID to a string for the Like comparison; however, this conversion does not now you want left-zero padding. To use this type of comparison, you need to format ID yourself.
Select * From [sheet1$] Where (Format([ID], ""000000000"") Like '" & prod & "%')"
As you have indicated in the comments above, this works. However, it is not the most efficient in terms of speed. Since ID is numeric, it should be faster to do a numeric comparison. You have already defined a String variable named prod and the following solution uses that variable to prepare a numeric value for use in constructing an alternate select based on your criteria.
Dim prodNum As Int32 = Int32.Parse(prod) * 10000I
Then the Select statement would become:
"Select * From [sheet1$] Where ((([ID]\10000) * 10000)=" & prodNum.ToString & ")"
These examples use a concatenated select statement, and ideally you would not do it this way, but rather use a parameterized statement with replacement values. I'll leave that exercise up to you to perform.

Unable to insert string into Access database

I am using a WPF application to insert a student into my MS Access database.
I wanted to use a parameter with this code:
Dim sql As String = _
"INSERT INTO exams " & _
"VALUES (#student)"
Dim opdracht As OleDbCommand = New OleDbCommand(sql, connectie)
opdracht.Parameters.Add(New OleDbParameter("#student", 5))
but this doesn't work.
The only way i get it to work is this one:
Dim sql As String = _
"INSERT INTO exams " & _
"VALUES (" & student & ")"
' opdracht initialiseren
Dim opdracht As OleDbCommand = New OleDbCommand(sql, connectie)
To use this query I use the command, this is the point where I get my error.
opdracht.executeNonQuerry()
The table layout in MS Access looks like this:
And my application inserts the other values corectly but i left them out to keep a minimal example.
If you have a variable named student and you want to use its value for the parameter then you need to assign that variable as parameter's value
Dim sql As String = "INSERT INTO exams VALUES (#student)"
Dim opdracht As OleDbCommand = New OleDbCommand(sql, connectie)
opdracht.Parameters.AddWithValue("#student", student)
opdracht.ExecuteNonQuery()
Of course, I am assuming this because you say that the string concatenation version is working, and in that example you concatenate the value of a variable named student in your command text
Remember that with OleDb the name of your parameters is meaningless because OleDb use the position of the placeholder to pass the parameters' values, not the parameter name
EDIT Using INSERT INTO without specifying the column names works only if you add the parameters for all fields. Your database table contains other fields so you need to specify them or use a different syntax for the INSERT INTO
Dim sql As String = "INSERT INTO exams (Student) VALUES (#student)"
But this will fail also because you have the Student field part of your primary key. The fields that belong to a Primary Key cannot be null so you have no choice but add all the values required by the primary key
Dim sql As String = "INSERT INTO exams (Student, locaal, opleidingsOnderdeel) " & _
"VALUES (#student, #local, #oplei)"
.. add the parameter's value for student, local and oplei
However, I am a bit perplexed that the string concatenation works. What is the value of the variable student? You should get the same error as using the parameterized query with only one parameter.

query pulls from textbox and sets column name from combo box

I am coding in vb on visual studio 2012 and I need to create a query that pulls table data into a datagriddview. I have a textbox for user input and a combobox to set what the column name. Sort of like, "SELECT * FROM TITLES WHERE COMBOBOX LIKE TEXTBOX". I apologize if this question is old ground for you but I looked everywhere and couldn't find what I was looking for. Also I am a total newb so please speak slowly and in small words. Thanks in advance for your help.
You need to modify your SQL to be:
"SELECT * FROM TITLES WHERE " & ComboBox1.Text & " LIKE '%" & TextBox1.Text & "%'"
Deja Vu's answer should be ok. You may take it a step further, and try using a parameter instead of building the sql string directly from users' direct input, thus avoiding SQL Injection (which is a security risk):
Dim Sql As String = "SELECT * FROM MYTABLE WHERE " & ComboBox1.Text & " LIKE '%?%' "
Dim p As New OleDb.OleDbParameter : p.Value = Textbox1.text
Dim OleDBCommand As New OleDb.OleDbCommand(Sql, Connection)
OleDBCommand.Parameters.Add(p)
Dim da As New OleDb.OleDbDataAdapter(OleDBCommand)
Dim DT As New DataTable
da.Fill(DT)
(Note: I'm assuming this is an Application and users must choose an item from the combobox, and they cannot change the content of the combobox.)

Error in My Add button SQL Server Management Studio And Visual Basic 2010

Here is the thing I can't use insert query in my code there is an error in my SqlCommand that says the ExecuteNonQuery() not match with the values blah blah
Here is my code
Dim con As New SqlClient.SqlConnection("Server=.\SQLExpress;AttachDBFilename=C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\Finals.mdf;Database=Finals;Trusted_Connection=Yes;")
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = con
cmd.CommandText = "Insert Into [Finals].[dbo].[Nokia] Values ('" & Unit.Text & "'),('" & Price.Text & " '),('" & Stack.Text & "'),('" & Processor.Text & "'),('" & Size.Text & "'),('" & RAM.Text & "'),('" & Internal.Text & "'),('" & ComboBox1.Text & "')"
con.Open()
cmd.ExecuteNonQuery()
con.Close()
The problem is the cmd.CommandText can anyone please help me?
You need to rewrite your query to use a parameterized query. This would avoid parsing problems if your textboxes contains single quotes and, most important, would remove any possibility of Sql Injection.
So you code could look like this
Dim cmdText = "Insert Into [Finals].[dbo].[Nokia] Values (#unit, #price,#stack," & _
"#processor,#size,#ram,#internal,#lastvalue"
Using con As New SqlConnection(......)
Using cmd As New SqlCommand(cmdText, con)
con.Open()
cmd.Parameters.AddWithValue("#unit",Unit.Text )
cmd.Parameters.AddWithValue("#price",Price.Text)
cmd.Parameters.AddWithValue("#stack",Stack.Text)
cmd.Parameters.AddWithValue("#processor", Processor.Text)
cmd.Parameters.AddWithValue("#size",Size.Text)
cmd.Parameters.AddWithValue("#ram", RAM.Text)
cmd.Parameters.AddWithValue("#internal",Internal.Text)
cmd.Parameters.AddWithValue("#lastvalue", ComboBox1.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Said that, be aware of two more problems:
You don't specify a column list before the VALUES statement. This means that you need to pass the exact number of parameters for every column present in your table named Nokia AND in the EXACT ORDER of the underlying columns. If you forget one parameter you will receive an exception and if you swap the order of the parameters you end writing your data in the wrong column (with an exception waiting for you if the datatype doesn't match).
The second problem concerns the datatype of every parameter passed to the query. In your case you use the Text property of the textboxes and this means that you are passing a string for every column in the datatable. Of course, if a column expects a numeric value you get a mismatch error.
For example the #price parameter could be used to update a decimal column in the datatable and thus you need to convert the parameter from string to decimal before adding it using the AddWithValue method
cmd.Parameters.AddWithValue("#price",Convert.ToDecimal(Price.Text))

how to get data to textbox from the database

I have a form with one combo box and text box, and an SQL database
named balance with two columns; one as customername and the other as obbalance.
I had bound all of the customer name to the combo box, now what I have to do is,
when a user selects a customer name from the combo box, the text box should show the obbalance of the selected customername; here, the customer name will not be repeated - only one name per customer.
What can I do? Please help me.
Dim conectionstring As String
conectionstring = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\SHOPPROJECT\SHOPPROJECT\shop.mdf;Integrated Security=True;User Instance=True"
Dim ST As String = ComboBox1.SelectedText
Dim sqlcon As New SqlConnection(conectionstring)
Dim sqlcmd As New SqlCommand("SELECT OBBALANCE FROM BALANCE WHERE CUSTOMERNAME = " & " '" & ST & "'" & "", sqlcon)
MessageBox.Show(TextBox1.Text)
Dim result As Object
Try
sqlcon.Open()
' Dim sdr As SqlDataReader = sqlcmd.ExecuteReader()
result = sqlcmd.ExecuteScalar()
If result IsNot Nothing Then
TextBox1.Text = result.ToString()
MessageBox.Show(TextBox1.Text)
End If
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
End Sub
I've tried this, but I can't see the value in the text box, and obbalance is a floating-point value from the SQL database.
If you're updating a text box, is this a single result (scalar value)? If so, the first thing I'd do is use ExecuteScalar not ExecuteReader. Then, use debug mode with breakpoints to get a better idea of what is actually happening. It may simply be that you're not getting any results.
Note: I'm assuming the bad coding practice (in-line sql statement, hard-coded connection string, etc.) are for clarity. If they're not, fix them.
Make the follwing changes:
Dim sqlcmd As New SqlCommand("SELECT OBBALANCE FROM BALANCE WHERE CUSTOMERNAME = '" & ST & "'", sqlcon)
TextBox1.Text = sdr.GetString(yourColumnIndex)
ComboBox1.SelectedText returns the highlighted (selected) text on the ComboBoxControl. That will be empty if you haven't use your mouse to select a portion of its text or hold the shift while you are pressing the direction keys on your keyboard. And that's probably why your query returns ZERO RECORDS.
Use the following instead:
Dim ST As String = ComboBox1.SelectedItem.Text
Set a breakpoint and ensure you are getting the value for OBBALANCE (see if you are getting any rows period might be good). Also, make sure you can only get one row, as you are iterating forward, even when you only need one value.
Better yet, consider ExecuteScalar, which only returns a single value. While you are at it, parameterize the SQL query so you don't get SQL injected.
UPDATE: Just change it here:
sdr = sqlcmd.ExecuteReader()
to something like
Dim s as String = sqlcmd.ExecuteScalar()
Then use s as your textbox value. You may have to ToString() the value or otherwise cast as string, as I believe the ExecuteScalar() returns an object.