Strange Update clause error (VB.NET) - vb.net

I'm experiencing a really strange error. I have a table with only two columns (User and pass , both with text type).
The program asks first, what column I want to modify. With a radio button , I point which column I want to modify.
By pressing any radio button, two text boxes appear . You have to enter the password and the new data to modify it.
The problem is that when making the modification , if I want to change the user column , all is work well... But if I want to change a thing of the Password column , release "update error clause".
Honestly, I do not see any error in this code:
Protected Friend Sub modificarAcesso(ByVal column As String, ByVal dato As String)
Dim cmd As String = "Update Login SET " & column & "=#dato"
Try
con.Open()
comando = New OleDbCommand(cmd, con)
comando.Parameters.AddWithValue("#dato", dato)
comando.ExecuteNonQuery()
comando.Dispose()
con.Close()
Catch ex As Exception
con.Close()
MsgBox("Problemas en la consulta: " + ex.Message(), MsgBoxStyle.Critical)
End Try
End Sub

Password is a keyword, so you must put it in brackets. You should do this anyway if a column name has a space in it, too:
Dim cmd As String = "Update Login SET [" & column & "] = #dato"

Related

VB.NET database is not in MS Access and login error

I use Microsoft Access to store the data. The register form shows msgbox that the data was saved but there isn't any data stored in the table when I check the table on Microsoft Access. Is it supposed to be like that or did I code wrong?
This is my register code
If PasswordTextBox.Text.Length >= 8 Then
Try
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database2.accdb")
Dim insert As String = "Insert into Table1 values('" & NameTextBox.Text & "','" & Staff_IDTextBox.Text & "','" & Phone_NoTextBox.Text & "','" & UsernameTextBox.Text & "','" & PasswordTextBox.Text & "');"
Dim cmd As New OleDbCommand(insert, conn)
conn.Open()
'cmd.ExecuteNonQuery()
MsgBox("Saved")
For Each txt As Control In Me.Controls.OfType(Of TextBox)()
txt.Text = ""
Next
Catch ex As Exception
MsgBox("Error")
End Try
Else
MsgBox("Password must be more than 8 character")
End If
End If
This is my login code
uname = UsernameTextBox.Text
pword = PasswordTextBox.Text
Dim query As String = "Select password From Table1 where name= '" & uname & "';"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database2.accdb"
Dim conn = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
conn.Open()
Try
pass = cmd.ExecuteScalar().ToString
Catch ex As Exception
MsgBox("Username does not exit")
End Try
If (pword = pass) Then
MsgBox("Login succeed")
Else
MsgBox("Login failed")
UsernameTextBox.Clear()
PasswordTextBox.Clear()
End If
There is an error at this line
pass = cmd.ExecuteScalar().ToString
It says:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Your "cmd.ExecuteNonQuery" is commented out, so the code will not save anything to the database.
You should close your connection after executing the INSERT command.
By default the table will have auto-numbered field as the first item in the table. You will need to remove this field from your table for that specific INSERT command to work.
Or you may need to use a slightly different INSERT command. It is useful to have auto-numbered ID fields in a table.
You probably should catch the exception and display ex.Message in your message box rather then "Error". The ex.Message will be much more helpful to you in debugging your program.
I have made all of these mistakes in my code at one time or other.
Your Login Code;
1)
You should catch the exception message and display in it a message box. This will make debugging faster.
The actual exception in your code will read "{"No value given for one or more required parameters."}
Your query is incorrect.
You should do the open, query, and close of the connection inside the Try-Catch block. Test for a null password afterwards to determine if the username does not exist.
Two separate answers provided, because you have two very separate questions.
Best wishes...

How can I get my information to pass from my VB application to my Access Database table?

So this is the code that I am using:
Public Class Form1
Dim dtmSystemDate As Date
Dim strResult As String
Dim Student As Double = Nothing
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBeginWorkout.Click
Dim cnn As New OleDb.OleDbConnection
Dim cmd As New OleDb.OleDbCommand
Dim Start As String = "Start"
' Set date/time to today's date/time.
dtmSystemDate = Now()
' Convert txtIDNumber to a Double.
Try
Student = CDbl(txtIDNumber.Text)
Catch ex As Exception
End Try
' Determine if input is a valid ID number.
If Student >= 10000 And Student <= 99999 Then
MessageBox.Show("Your start time is " & dtmSystemDate.ToString("F"), "Welcome, Student # " & Student.ToString())
Else
MessageBox.Show("Please enter a valid College ID number", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Exclamation
)
End If
cnn.ConnectionString = "provider = microsoft.jet.oledb.4.0; data source = C:\users\econnelly\My Documents\Access Databases\Fit Track.mdb"
cnn.Open()
cmd.Connection = cnn
cmd.CommandText = "insert into Fit Track (Student_ID,Start/Stop,Date/Time) values ('" & Student & "','" & Start & "', '" & dtmSystemDate & "')"
cmd.ExecuteNonQuery()
cnn.Close()
I am attempting to pass these defined variables to an Access Database and so far have been unsuccessful.
Whenever I try to run my program, I get the following error:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
This error is triggering from the cmd.ExecuteNonQuery() function though I am not sure why.
As of yet, I have been unable to get the information to populate into the database at all. Can anyone point me in the right direction as to how to address this issue?
I believe the problem is with the table name "Fit Track" that has a space in it.
You could use square brackets like [Fit Track]
or you could use single quotes like 'Fit Track'
I don't know the answer, but I've ran into trouble when using spaces or special characters, like slashes, in database Table or Column names. Also, I think your connection string is incorrect. You might also want to read a little bit about SQL injection, it can be dangerous.
EDIT: You might also need to import System.Data.Oledb

Strange errors when making queries to excel

Im making an application in vb.net to connect to an Excel file and edit it.
At the moment attempting to modify the Excel file ,the following errors appear:
With this function
Protected Friend Function obtenerHojaActual(ByVal columna As String, ByVal con As String) As String
Dim cmd As String
Dim WorkSheet As String = ""
Try
libro = app.Workbooks.Open(con)
For Each hoja As Microsoft.Office.Interop.Excel.Worksheet In libro.Worksheets
cmd = "SELECT [" & columna & "] FROM [" & hoja.Name & "$]"
Dim adapter As New OleDbDataAdapter(cmd, conexion)
Dim tabla As New DataTable
adapter.Fill(tabla)
adapter.Dispose()
//Code
//Code
//Code
tabla.Dispose()
Next
libro.Close()
app.Quit()
Return WorkSheet
Catch ex As Exception
repairmanMessage("Error inesperado", ex.Message, My.Resources._error).ShowDialog()
principal.lbldireccion.ForeColor = Color.Red
Return WorkSheet
End Try
End Function
Got this:
"No specified values ​​for some of the parameters required"
And with this:
Protected Friend Function obtenerErrores(ByVal columna As String, ByVal hoja As String, ByVal tipo As String) As Integer
Dim cmd As String = "SELECT [" & columna & "] FROM [" & hoja & "$]"
Dim errores As Integer = 0
Dim fecha As Date
Dim tabla As New DataTable
Try
Dim adapter As New OleDbDataAdapter(cmd, conexion)
adapter.Fill(tabla)
adapter.Dispose()
//Code
//Code
//Code
tabla.Dispose()
Return errores
Catch ex As Exception
repairmanMessage("Error inesperado", ex.Message, My.Resources._error).ShowDialog()
principal.lbldireccion.ForeColor = Color.Red
Return errores
End Try
Get this error...
I tried using parameterized queries, but looks like excel dont works fine with that thing (or maybe, i dont know the syntax of the query of that to use with excel).
The strangest thing of all is that in other parts of the code , do not give me errors , the program just throws errors when Im trying to modify the file, and
although I get these two errors , excel sheet is modified just as I wanted ..
What can be ?
Ok , I sat down to check everything and I had to think a little about what was happening. I discovered that my code did not have any error (that's why even though the program gave me errors , the file is modified anyway)... and discovered this too, let me explain it with an Excel file example:
Im using in my connection string the HDR property ("HDR=Yes;" indicates that the first row contains columnnames, not data. "HDR=No;" indicates the opposite.) as you can see , I have defined 4 columns (Name, Last name, Date, Age... not more! ).
We run the program now with this sample file and look carefully what happens:
As we saw in the first picture , I've never created a column in that position ('F1') ... apparently , there are times where you create without realizing it what I call "phantom columns " in Excel . I imagine it as the first cell of the column has nothing written on it , the program automatically gives it its name, according to their position ('F1 ' is the ghost column).
To fix this problem , when I make a query, first I check if my parameter "column " is not empty.
Protected Friend Function obtenerHojaActual(ByVal columna As String, ByVal con As String) As String
If (Not String.IsNullOrEmpty(columna)) Then
//Blah blah
//Blah blah
//Blah blah
End If
Return "Desconocida"
End Function
And there we go!

Data type mismatch in criteria expression. -Microsoft JET DATABASE ENGINE

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

How to create a ComboBox autofill using SQLite Data Reader

I have two Combo-Boxes like this
I need to create an auto-fill feature for the 1st Combo-Box. It should list the EmployeeID if Search-By Field is specified as Employee-Number. Similarly it should list Employee First Name along with Last Name if the Search-By Field is Employee-Name.
How can I do this? I have no clue, I am doing this for the first time. I am using SQLite, Visual Studio 2010.
Dim mySelectQuery As String = "SELECT " & Search & " FROM EmployeeTable WHERE Status LIKE '" & Status & "'"
Dim myConnString As String = "Data Source=" & Application.StartupPath & "\Database\SimpleDB.db3"
Dim sqConnection As New SQLiteConnection(myConnString)
Dim sqCommand As New SQLiteCommand(mySelectQuery, sqConnection)
sqConnection.Open()
Try
' Always call Read before accessing data.
Dim sqReader As SQLiteDataReader = sqCommand.ExecuteReader()
Dim j As Integer = sqReader.FieldCount
While sqReader.Read()
'''''''''''''''''''''''Here, Don't know how to list the items from the query reult into the combo-box
End While
'Close Reader after use
sqReader.Close()
Catch ex As Exception
'Show Message on Error
MsgBox(ex.ToString)
Finally
'At Last Close the Connection
sqConnection.Close()
End Try
I'm not sure entirely what you are asking but I think this is it.
In the SelectedIndex changed event you would have something similar to the code below. You can add an If statement to check what you are querying for and adjust your query accordingly.
Dim dt as New DataTable
Try
Using sqlConn
sqlConn.Open()
Using cmd As New SqlCommand("your query")
cmd.Connection = sqlConn
cmd.CommandType = CommandType.Text
Dim reader as SqlDataReader = cmd.ExecuteReader()
dt.Load(reader)
End Using
End Using
Catch ex As SqlException
Throw New Exception(ex.Message)
End Try
With yourComboBox
.DataSource = dt
.DataValueField = "columName you want to be the value of the item"
.DataTextField = "columnName of the text you want displayed"
End With
Notice the following properties for the combo-box: AutoCompleteMode, AutoCompleteSource, AutoCompleteCustomSource.
Select the appropriate AutoCompleteMode. See details on the different modes at this link.
For AutoCompleteSource, choose either ListItems (in which case the source will be the items of the ComboBox) or CustomSource. Should you choose CustomSource, set the appropriate source as the value of the ComboBox's AutoCompleteCustomSource property.
This should provide you with enough details to do what you're looking for.
The other requirements you've listed - such as taking the data from an SQLite database or changing between employee name and employee number - won't affect the way you work with the AutoComplete feature.