How do I retrieve an ID field that is an AutoNumber and has been given an alphanumeric Format, e.g., 'ER001'?
I'm using Access for backend and VB 2010.
My code so far only returns the last number of the ID Column, e.g., 1 instead of ER001.
Dim SQL As String = "SELECT ID FROM ReqItemList WHERE ReqItem = " & inputin & " "
I believe that the confusion here is because the AutoNumber field "has alphanumeric format". If the table design looks like this
then the Format property "ER"000 for the ID field will cause it to appear in Access forms and datasheet views as something like ER001.
However, in Design View (the first screenshot) notice that the field is still an AutoNumber field and its "Field Size" is Long Integer. The values themselves are just numbers; they are merely being formatted as alphanumeric in the Access user interface.
So the behaviour you are seeing in your VB.NET application is "normal". If you run the query
Dim SQL As String = "SELECT ID FROM ReqItemList WHERE ReqItem=?"
Using cmd = New OleDbCommand(SQL, con)
cmd.Parameters.Add("?", OleDbType.VarWChar).Value = "foo"
Dim rtn = cmd.ExecuteScalar()
End Using
then you will get the Integer value 1, not the String value "ER001". If you want to have the value appear in your VB.NET forms as ER001 you will need to apply the formatting in your VB.NET code.
Similarly, if you want to search by ID then you will have to supply the unformatted numeric value. That is
Dim SQL As String = "SELECT ReqItem FROM ReqItemList WHERE ID=?"
Using cmd = New OleDbCommand(SQL, con)
cmd.Parameters.Add("?", OleDbType.Integer).Value = 1
Dim rtn As String = cmd.ExecuteScalar()
End Using
will return foo, whereas
Dim SQL As String = "SELECT ReqItem FROM ReqItemList WHERE ID=?"
Using cmd = New OleDbCommand(SQL, con)
cmd.Parameters.Add("?", OleDbType.VarWChar).Value = "ER001"
Dim rtn As String = cmd.ExecuteScalar()
End Using
will fail with "Data type mismatch in criteria expression" because ID is really a number, not a text value.
Related
This question already has answers here:
How can I add user-supplied input to an SQL statement?
(2 answers)
'No value given for one or more required parameters.' Error, Can't get over it
(2 answers)
Closed 2 years ago.
I have the issue with the following function:
Public Function collectuserid(conn, username)
Dim sql As String = "select ID from tblUserDetails where Username =" & username
Dim usersid As String = Nothing
Using connection As New OleDbConnection(conn)
Using command As New OleDbCommand(sql, connection)
connection.Open()
usersid = CStr(command.ExecuteNonQuery())
connection.Close()
End Using
End Using
Return usersid
End Function
The problem occurs in the following line:
usersid = CStr(command.ExecuteNonQuery())
The variable conn holds the connection string, and username holds a value for the username present in the database.
I want to collect the userid of the record, but cant seem to get it right. I have the exact same function open in another program with a different database and it works perfectly. All table and variable names are correct also. Any help?
Program for generating the record:
Sub insertuservalues(conn, a, b, c, d)
Dim sql As String = "INSERT INTO tblUserDetails(Name,Username,[Password],Email) VALUES (#name, #username, #password, #email)"
Using connection As New OleDbConnection(conn)
Using command As New OleDbCommand(sql, connection)
connection.Open()
command.Parameters.Add("#name", OleDbType.VarWChar).Value = a
command.Parameters.Add("#username", OleDbType.VarWChar).Value = b
command.Parameters.Add("#password", OleDbType.VarWChar).Value = c
command.Parameters.Add("#email", OleDbType.VarWChar).Value = d
command.ExecuteNonQuery()
connection.Close()
End Using
End Using
End Sub
Strictly speaking, the mistake you made was that you didn't wrap your literal text value within the SQL code in single quotes. Just as VB literal text must be wrapped in double quotes, so SQL literal text must be wrapped in single quotes:
Dim sql As String = "SELECT ID FROM tblUserDetails WHERE Username = '" & username & "'"
or:
Dim sql As String = String.Format("SELECT ID FROM tblUserDetails WHERE Username = '{0}'", username)
or:
Dim sql As String = $"SELECT ID FROM tblUserDetails WHERE Username = '{username}'"
If you do it the right way though, and follow the advice to use parameters, this becomes redundant. ALWAYS use parameters to avoid formatting issues, special character issues and, most importantly, SQL injection issues.
You need single quotes around string values in the SQL. But don't do that! Instead, define this as a query parameter:
Public Function collectuserid(conn As String, username As String) As String
'No string concatentation!
' Also, OleDb tends to use ? placeholders for positional parameters, rather than parameter names.
Dim sql As String = "select ID from tblUserDetails where Username = ?"
Using connection As New OleDbConnection(conn)
Using command As New OleDbCommand(sql, connection)
'Use the actual type and length from the database here
command.Parameters.Add("username", OleDbtype.VarWChar, 20).Value = username
connection.Open()
Return CStr(command.ExecuteNonQuery())
'No need to call connection.Close()
' The Using block guarantees the connection will close, even though we Return before reaching the end of it.
End Using
End Using
End Function
I want to search for a keyword on 4 columns like :
Dim con As OleDbConnection
Dim cmd As OleDbCommand
con=new OleDbConnection (connectionstring)
cmd=new OleDbCommand (Select * from DVD_INFO where slot 1 = ' "+TXTSearch .Text+" ' OR slot 2 = ' "+TXTSearch .Text+" ' ...etc)
con.open ()
dr=cmd.ExecuteReader
While dr.read
txtDVDno.Text = dr ("DVD no")
End While
con.Close ()
Error Message
syntax error (missing operator) in query expression 'Slot 1 = 'Iron Man"
MsgName is OleDbException was Unhandled
How can i fix this issue?
Field names with spaces should be enclosed in square brackets
cmd=new OleDbCommand (Select * from DVD_INFO where [slot 1] = ....."
Said that, start as soon as possible to use a parameterized query to avoid sql injection security problems and parsing problems
Dim cmdText = "Select * from DVD_INFO where [slot 1] = #search"
Using con=new OleDbConnection (connectionstring)
using cmd=new OleDbCommand (cmdText, con)
con.open()
cmd.Parameters.Add("#search", OleDbType.VarWChar).Value = TXTSearch.Text
Using dr=cmd.ExecuteReader()
While dr.read
txtDVDno.Text = dr("DVD no")
End While
End Using
End Using
End Using
Note that if you want to repeat the search on other fields you need to add another parameter for each condition also if it is the same value repeated more than one time. This is necessary with OleDb because this driver is not able to recognize the parameters by their placeholder name. It uses a strictly positional order and so, if you have two where condition you need to add two parameters to the collection no matter what is their name or value.
EDIT
If you want to execute the search having only a partial text you could use the LIKE operator in your query text and change the way in which you initialize the parameters adding the wildcard symbol %
Dim cmdText = "Select * from DVD_INFO where [slot 1] LIKE #search"
....
cmd.Parameters.Add("#search", OleDbType.VarWChar). Value = TXTSearch.Text & "%"
Of course the wildcard character could be added at the beginning of the searched text to give different meanings to your search text (field begins, ends, contains)
How do you use SQL to put data into an empty table? So far in my code I have taken the data from an SQL table and then have put it into a Text Box using the following code:
Dim query As String = "SELECT Pronunciation, Character FROM [Katakana List] WHERE Pronunciation='" & pronunciation & "';"
Dim instruction = New SqlCommand(query, sqlCon)
Dim da As New SqlDataAdapter
da.SelectCommand = instruction
da.Fill(Katakana)
Textbox1.text=DT.row(0)("column")
Now that the data is held in the text box, how would I do the reverse of this process to put the data into an empty table. It would help if someone could give me an example of the query I could use to put the data back in.
If you want update data which you get from query before, then use UPDATE-query
If you want insert brand new data then use INSERT - query
'For updating existing data
Dim query As String = "UPDATE [Katakana List] SET Character = #NewCharacter WHERE Pronunciation=#Pronunciation"
'For Inserting new data
Dim query As String = "INSERT INTO [Katakana List] (Character) VALUES (#NewCharacter);"
Using instruction As New SqlCommand(query, sqlCon)
'Better practice to use parameters in query
instruction.Parameters.AddWithValue("#Pronunciation", pronunciation)
instruction.Parameters.AddWithValue("#NewCharacter", Textbox1.text)
instruction.ExecuteNonQuery()
End Using
If you want to set the data in the textbox into datatable just do it like this :
DT.row(0)("column") = Textbox1.text
if you want to enter it into database create query to do so , something like this :
Dim query As String = "Insert Into TableName(col1) Values('"& Textbox1.text &"');"
Dim command = New SqlCommand(query, sqlCon)
command.ExecuteNonQuery()
In the code below, it was a "delete" button used in OLEDB connection.
My database table name is tblinformation.
Btw, the error shows:
Data type mismatch in criteria expression. `-Microsoft JET DATABASE ENGINE`, and it was in a form of msgbox..
Imports System.Data.OleDb
Imports System.String
Public Class frmbookinfo
Dim cnn As New OleDb.OleDbConnection
Dim Str As String
If CheckId() = False Then
MsgBox("Id : Integer Value Required!!!")
Exit Sub
End If
Try
Str = "delete from tblinformation where bcode="
Str += txtbookcode.Text.Trim
Con.Open()
Cmd = New OleDbCommand(Str, Con)
Cmd.ExecuteNonQuery()
Dst.clear()
Dad = New OleDbDataAdapter("SELECT * FROM tblinformation ORDER BY bcode", Con)
Dad.Fill(Dst, "tblinformation")
MsgBox("Record deleted successfully...")
If CurrentRow > 0 Then
CurrentRow -= 1
ShowData(CurrentRow)
End If
Con.Close()
Catch ex As Exception
MessageBox.Show("Could Not delete Record!!!")
MsgBox(ex.Message & " - " & ex.Source)
Con.Close()
End Try
Probably your field bcode in the database is of type text.
You use a string concatenation to build your command text and this cannot be helped if you fail to treat your values correctly.
Instead use parametrized queries and leave the task to correctly parse your parameters to the database framework code
Str = "delete from tblinformation where bcode=?"
Con.Open()
Cmd = New OleDbCommand(Str, Con)
Cmd.Parameters.AddWithValue("#p1", txtbookcode.Text.Trim)
Cmd.ExecuteNonQuery()
Now your sql command contains a parameter placeholder (?) and the correct parameter value is assigned in the parameter collection. The framework code handles correctly this parameter
EDIT If your bcode field is a text field, you cannot build your command in that way. You should encapsulate your value between single quotes. Something like this.
IT WORKS BUT IT IS WRONG - VERY WRONG -
Str = "delete from tblinformation where bcode='" & txtbookcode.Text.Trim & "'"
But this is wrong from the start.
First - If your txtbookcode contains a single quote, the whole
command text becomes invalid and you get a Syntax Error
Second - String concatenation is bad because you can't trust your user.
If it enters some malicious text you could face a Sql Injection
problem
So, I really suggest you to use the parametrized query approach illustrated in the first example
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.