Data type mismatch in criteria expression while updating password field - sql

This is my Select & Update code for OLEDB DB.
I am getting a Data type mismatch in criteria expression error whilst changing the Password field value.
All four fields are set to Long Text datatype.
Update Query
con = Class1.dbconn
cmd = New OleDbCommand("Update User_details set User_ID ='" & TextBox1.Text & "', User_Name='" & TextBox2.Text & "', [Password]='" & TextBox3.Text & "' where Sno='" & Label4.Text & "'", con)
cmd.ExecuteNonQuery()
MessageBox.Show("User Details Updated")
Select Query
cmd = New OleDbCommand("select * from User_details where User_ID='" & TextBox1.Text & "'", con)
Dim dr As OleDbDataReader
dr = cmd.ExecuteReader
If dr.Read Then
Label4.Text = dr("Sno").ToString
TextBox2.Text = dr("User_Name").ToString
TextBox3.Text = dr("Password").ToString
TextBox2.Text = TextBox2.Text.Replace(" ", "")
TextBox3.Text = TextBox3.Text.Replace(" ", "")
dr.Close()
End If

Keep your database objects local so you can control when they are closed and disposed. Using...End Using blocks take care of this for you even if there is an error. The Using blocks demonstrated here take care of both the connection and the command. Note the comma after the connection line.
Always use Parameters. Not only does it make your command text easier to read and write (without all the quotes, double quotes and ampersands) but it protects your database from the destruction of Sql injection. When you are using the OleDb provider it is essential that order that the parameters appear in the command text match the order they are added to the parameters collection. Unlike Sql Server, Access pays no attention to the names of the parameters; only the order.
Notice that the connection is not opened until right before the .Execute... and is closed (with the End Using) directly after. Connections are precious resources. I used a DataTable instead of a DataReader in the SelectUser sub so I could close the connection before updated the user interface. In the UpdatePassword sub the connection is closed before showing the MessageBox. After all the end user could have gone to lunch and there would be your connection flapping in the breeze.
As far as the type mis-match check the links provided by #Jimi and then check your database to see if the OleDbType matches.
Private Sub UpdatePassword()
Using con As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand("Update User_details set User_ID = #ID, User_Name = #Name, [Password]= #Password Where Sno= #Sno;", con)
With cmd.Parameters
.Add("#ID", OleDbType.LongVarChar).Value = TextBox1.Text
.Add("#Name", OleDbType.LongVarChar).Value = TextBox2.Text
.Add("#Password", OleDbType.LongVarChar).Value = TextBox3.Text
.Add("#Sno", OleDbType.LongVarChar).Value = Label4.Text
End With
con.Open()
cmd.ExecuteNonQuery()
End Using
MessageBox.Show("User Details Updated")
End Sub
Private Sub SelectUser()
Dim dt As New DataTable
Using con As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand("select * from User_details where User_ID= #ID;", con)
cmd.Parameters.Add("#ID", OleDbType.LongVarChar).Value = TextBox1.Text
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count > 0 Then
Dim row As DataRow = dt.Rows(0)
Label4.Text = row("Sno").ToString
TextBox2.Text = row("User_Name").ToString
TextBox3.Text = row("Password").ToString
TextBox2.Text = TextBox2.Text.Replace(" ", "")
TextBox3.Text = TextBox3.Text.Replace(" ", "")
End If
End Sub
Finally, you should NEVER store passwords as plain text. They should be salted and hashed. I will leave it to you to research how to do this.

Related

How to save integer and decimal datatype from datagridview to database ms access in VB.NET [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 3 years ago.
I have been searching for a solution for my code error, which says that there is a data mismatch to my database declared datatype. I am saving my data grid view's data into ms access database but it show an error of data mismatch for saving PRICE and QUANTITY data.
I have tried adding parameters and it shows the error System.NullReferenceException: 'Object reference not set to an instance of an object.'
'After comfirm only save in database
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If (MessageBox.Show("Comfrim the orders?", "Comfirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes) Then
If OrderDataGridView.Rows.Count > 0 Then
DBConnect = New OleDbConnection
DBConnect.ConnectionString = "Provider=Microsoft.jet.oledb.4.0;data source = ViewOrder.mdb"
For i As Integer = OrderDataGridView.Rows.Count - 1 To 0 Step -1
Dim Query As String
Query = "INSERT INTO ViewOrder.Order (Serve,Table_No, Item_Code, Item_Name, Quantity, Price, Remarks)
VALUES (#Serve, #Table_No, #Item_Code, Item_Name, #Quantity, #Price, #Remarks)"
Dim cmd As New OleDb.OleDbCommand(Query, DBConnect)
cmd.Parameters.Add("#Serve", OleDbType.VarChar).Value = Label8.Text
cmd.Parameters.Add("#Table_No", OleDbType.VarChar).Value = Label10.Text
cmd.Parameters.Add("#Item_Code", OleDbType.VarChar).Value = OrderDataGridView.Rows(i).Cells(0).Value
cmd.Parameters.Add("#Item_Name", OleDbType.VarChar).Value = OrderDataGridView.Rows(i).Cells(1).Value
cmd.Parameters.Add("#Quantity", OleDbType.Integer).Value = OrderDataGridView.Rows(i).Cells(2).Value
cmd.Parameters.Add("#Price", OleDbType.Decimal).Value = OrderDataGridView.Rows(i).Cells(3).Value
cmd.Parameters.Add("#Remarks", OleDbType.VarChar).Value = OrderDataGridView.Rows(i).Cells(4).Value
DBConnect.Open()
Dim Reader As OleDbDataReader
Reader = command.ExecuteReader
DBConnect.Close()
Next
End If
End If
End Sub
But it still show the error.
This is my current code with the error of data mismatch.
Dim Query As String
Query = "INSERT INTO ViewOrder.Order (Serve,Table_No, Item_Code, Item_Name, Quantity, Price, Remarks) VALUES ('" & Label8.Text & "','" & Label10.Text & "','" & OrderDataGridView.Rows(i).Cells(0).Value & "', '" & OrderDataGridView.Rows(i).Cells(1).Value & "','" & OrderDataGridView.Rows(i).Cells(2).Value & "','" & OrderDataGridView.Rows(i).Cells(3).Value & "','" & OrderDataGridView.Rows(i).Cells(4).Value & "')"
Dim Reader As OleDbDataReader
command = New OleDbCommand(Query, DBConnect)
Reader = command.ExecuteReader
DBConnect.Close()
I just need to save the data in database.
From the MS Docs
the order in which OleDbParameter objects are added to the
OleDbParameterCollection must directly correspond to the position of
the question mark placeholder for the parameter in the command text.
Instead of question marks, I like to use parameter names. It is easier to see if I have the order correct. We add the parameters outside the loop because each iteration uses the same parameters. We don't want to keep adding them. Only the values change but not for Serve and TableNo which stay the same for all the Inserts.
Pass the connection string directly to the constructor of the connection.
The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
You do not want a reader for an Insert. A reader is for returned records. You need .ExecuteNonQuery.
You need to check the datatypes of the fields because I just guessed.
The DataGridView.Rows.Count is -2 because subtract one for counting starting at one and collections starting at zero. And subtract another one for the empty row at the bottom of the grid that is included in the count.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Query As String = "INSERT INTO ViewOrder.Order (Serve,Table_No, Item_Code, Item_Name, Quantity, Price, Remarks)
Values(#Serve, #TableNo, #ItemCode,#ItemName, #Quantity, #Price, #Remarks);"
Using DBConnect = New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source = ViewOrder.mdb")
Using cmd As New OleDbCommand(Query, DBConnect)
cmd.Parameters.Add("#Serve", OleDbType.VarChar).Value = Label8.Text
cmd.Parameters.Add("#TableNo", OleDbType.VarChar).Value = Label10.Text
cmd.Parameters.Add("#ItemCode", OleDbType.VarChar)
cmd.Parameters.Add("#ItemName", OleDbType.VarChar)
cmd.Parameters.Add("#Quantity", OleDbType.Integer)
cmd.Parameters.Add("#Price", OleDbType.Decimal)
cmd.Parameters.Add("#Remarks", OleDbType.VarChar)
DBConnect.Open()
For i As Integer = 0 To DataGridView1.Rows.Count - 2
cmd.Parameters("#ItemCode").Value = OrderDataGridView.Rows(i).Cells(0).Value
cmd.Parameters("#ItemName").Value = OrderDataGridView.Rows(i).Cells(1).Value
cmd.Parameters("#Quantity").Value = CInt(OrderDataGridView.Rows(i).Cells(2).Value)
cmd.Parameters("#Price").Value = CDec(OrderDataGridView.Rows(i).Cells(3).Value)
cmd.Parameters("#Remarks").Value = OrderDataGridView.Rows(i).Cells(4).Value
cmd.ExecuteNonQuery()
Next
End Using
End Using
End Sub

No value given for one or more required parameters error vb.net

no_hp = TextBox1.Text
alamat = TextBox2.Text
password = TextBox3.Text
cmd = New OleDbCommand("UPDATE [user] SET no_hp = '" & CInt(TextBox1.Text) & "',alamat = " & TextBox2.Text & ", pin ='" & CInt(TextBox3.Text) & "' WHERE id = " & id & "", conn)
cmd.Connection = conn
cmd.ExecuteReader()
i was trying to update my access database with the following error
i cant seem to see where i did wrong
i already changed the data type from the textbox to match with the data types used in the database
the no_hp and pin is integer so i converted it to Cint but it doesnt seem to work
i already tried to substitute it to a variable but still it didnt work
please tell me where i did wrong
Use Parameters to avoid SQL injection, a malious attack that can mean data loss. The parameter names in Access do not matter. It is the order that they are added which must match the order in the SQL statement that matters.
The Using...End Using statements ensure that you objects are closed and disposed even it there is an error. This is most important for connections.
You con't need to set the connection property of the command because you passed the connection in the constructor of the command.
ExcuteReader is for retrieving data. Use ExecuteNonQuery to update, insert of delete.
Private Sub UpdateUsers()
Using conn As New OleDbConnection("Your connection string")
Using cmd = New OleDbCommand("UPDATE [user] SET no_hp = ?,alamat = ?, pin =? WHERE id = ?", conn)
cmd.Parameters.Add("nohp", OleDbType.Integer).Value = CInt(TextBox1.Text)
cmd.Parameters.Add("alamat", OleDbType.VarChar).Value = TextBox2.Text
cmd.Parameters.Add("pword", OleDbType.Integer).Value = CInt(TextBox3.Text)
cmd.Parameters.Add("id", OleDbType.Integer).Value = id
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End Sub

How to determine if a record already exists in VB.net?

I'm doing a VB with Access database and I want to create a button. Which savebutton with checking where the data that try to insert is duplicated or not compare with my database.
This my code, and the problem is whatever I enter it just show the user already exists.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
MyConn.Open()
If (ComboBox2.Text = "") And (ComboBox3.Text = "")
And (TextBox3.Text = "") And (ComboBox4.Text = "")
Then
MsgBox("Please fill-up all fields!")
Else
Dim theQuery As String = ("SELECT * FROM Table1
WHERE"" [Subject_Code]=#Subject_Code ,[Day]=#Day,
[Times]=#Times , [Lecture]=#Lecture and [Class_Room]=#Class_Room""")
Dim cmd1 As OleDbCommand = New OleDbCommand(theQuery, MyConn)
cmd1.Parameters.AddWithValue("#Subject_Code", TextBox6.Text)
cmd1.Parameters.AddWithValue("#Day", ComboBox2.Text)
cmd1.Parameters.AddWithValue("#Times", ComboBox3.Text)
cmd1.Parameters.AddWithValue("#Lecture", TextBox3.Text)
cmd1.Parameters.AddWithValue("#Class_Room", ComboBox4.Text)
Using reader As OleDbDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
'User already exists
MsgBox("User Already Exist!")
Else
Dim Update As String = "INSERT INTO [Table1]
([Subject_Code], [Subject],
[Day], [Times], [Level],[Semester], [Lecture],[Class], [Class_Room])
VALUES (?,?,?,?,?,?,?,?,?)"
Using cmd = New OleDbCommand(Update, MyConn)
cmd.Parameters.AddWithValue("#p1", TextBox6.Text)
cmd.Parameters.AddWithValue("#p2", TextBox1.Text)
cmd.Parameters.AddWithValue("#p3", ComboBox2.Text)
cmd.Parameters.AddWithValue("#p4", ComboBox3.Text)
cmd.Parameters.AddWithValue("#p5", ComboBox1.Text)
cmd.Parameters.AddWithValue("#p6", ComboBox6.Text)
cmd.Parameters.AddWithValue("#p7", TextBox3.Text)
cmd.Parameters.AddWithValue("#p8", ComboBox5.Text)
cmd.Parameters.AddWithValue("#p9", ComboBox4.Text)
MsgBox("New Data Is Saved")
cmd.ExecuteNonQuery()
End Using
End If
End Using
End If
First of all take a quick look at your theQuery variable, it may just have been malformed from where you have typed it into SO, but if not try:
Dim theQuery As String = "SELECT * FROM Table1 " &
"WHERE [Subject_Code] = #Subject_Code " &
"AND [Day] = #Day " &
"AND [Times] = #Times " &
"AND [Lecture] = #Lecture " &
"AND [Class_Room] = #Class_Room"
Your check for a pre existing user is based upon 5 fields, the insert for new data has 9 fields. Without knowing the business case I can't be sure if this is correct or if the missing 4 fields are actually important to the check and causing unexpected rows to be returned.
Personally my next steps would be:
Put a breakpoint on the AddWithValue statements and check the values
are what you expect
Run the query with the values in SSMS/Access or equivalent and check the rows that come back are what you expect

ExecuteReader: CommandText property has not been initialized when trying to make a register form for my database

hello guys im trying to script a register form for my database and i came with this code >> so can anyone help ?
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
cn.ConnectionString = "Server=localhost;Database=test;Uid=sa;Pwd=fadyjoseph21"
cmd.Connection = cn
cmd.CommandText = "INSERT INTO test2(Username,Password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
cn.Open()
dr = cmd.ExecuteReader
If dr.HasRows Then
MsgBox("You're already registered")
Else
MsgBox("Already registered")
End If
End Sub
Edit your Code in this way..
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' , '" & TextBox2.Text & "')"
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
Insert will not retrieve any records it's a SELECT statement you want to use .I'll suggest you use stored procedures instead to avoid Sql-Injections.
ExecuteReader it's for "SELECT" queries, that helps to fill a DataTable. In this case you execute command before cmd.commandText is defined.
You should have define cmd.commandText before and use ExecuteNonQuery after, like this.
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
cn.ConnectionString = "Server=localhost;Database=test;Uid=sa;Pwd=fadyjoseph21"
cmd.Connection = cn
cn.Open()
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
cmd.ExecuteNonQuery()
cn.Close()
cmd.CommandText should be assigned stored proc name or actual raw SQL statement before calling cmd.ExecuteReader
Update:
Change code as follows
....
cmd.Connection = cn
cmd.CommandText = "select * from TblToRead where <filter>" ''This is select query statement missing from your code
cn.Open()
dr = cmd.ExecuteReader ....
where <filter> will be something like username = "' & Request.form("username') & '" '
The error itself is happening because you're trying to execute a query before you define that query:
dr = cmd.ExecuteReader
'...
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
Naturally, that doesn't make sense. You have to tell the computer what code to execute before it can execute that code:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
'...
dr = cmd.ExecuteReader
However, that's not your only issue...
You're also trying to execute a DataReader, but your SQL command doesn't return data. It's an INSERT command, not a SELECT command. So you just need to execute it directly:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
cmd.ExecuteNonQuery
One value you can read from an INSERT command is the number of rows affected. Something like this:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
Dim affectedRows as Int32 = cmd.ExecuteNonQuery
At this point affectedRows will contain the number of rows which the query inserted successfully. So if it's 0 then something went wrong:
If affectedRows < 1 Then
'No rows were inserted, alert the user maybe?
End If
Additionally, and this is important, your code is wide open to SQL injection. Don't directly execute user input as code in your database. Instead, pass it as a parameter value to a pre-defined query. Basically, treat user input as values instead of as executable code. Something like this:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES(#Username,#Password)"
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 50).Value = TextBox1.Text
cmd.Parameters.Add("#Password", SqlDbType.NVarChar, 50).Value = TextBox2.Text
(Note: I guessed on the column types and column sizes. Adjust as necessary for your table definition.)
Also, please don't store user passwords as plain text. That's grossly irresponsible to your users and risks exposing their private data (even private data on other sites you don't control, if they re-use passwords). User passwords should be obscured with a 1-way hash and should never be retrievable, not even by you as the system owner.
You're attempting to change the CommandText after you're executing your query.
Try this:
Private cn = New SqlConnection("Server=localhost;Database=test;UID=sa;PWD=secret")
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cmd As New SqlCommand
cmd.CommandText = "select * from table1" ' your sql query selecting data goes here
Dim dr As SqlDataReader
cmd.Connection = cn
cn.Open()
dr = cmd.ExecuteReader
If dr.HasRows = 0 Then
InsertNewData(TextBox1.Text, TextBox2.Text)
Else
MsgBox("Already registered")
End If
End Sub
Private Sub InsertNewData(ByVal username As String, ByVal password As String)
Dim sql = "INSERT INTO User_Data(Username,Password) VALUES(#Username, #Password)"
Dim args As New List(Of SqlParameter)
args.Add(New SqlParameter("#Username", username))
args.Add(New SqlParameter("#Password", password))
Dim cmd As New SqlCommand(sql, cn)
cmd.Parameters.AddRange(args.ToArray())
If Not cn.ConnectionState.Open Then
cn.Open()
End If
cmd.ExecuteNonQuery()
cn.Close()
End Sub
This code refers the INSERT command to another procedure where you can create a new SqlCommand to do it.
I've also updated your SQL query here to use SqlParameters which is much more secure than adding the values into the string directly. See SQL Injection.
The InsertNewData method builds the SQL Command with an array of SQLParameters, ensures that the connection is open and executes the insert command.
Hope this helps!

SQL injection-proofing TextBoxes

I've found some tutorials on this already, but they aren't exactly what I'm looking for, I can use the following for username fields and password fields
Private Sub UsernameTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles UsernameTextBox.KeyPress
If Char.IsDigit(e.KeyChar) OrElse Char.IsControl(e.KeyChar) OrElse Char.IsLetter(e.KeyChar) Then
e.Handled = False
Else
e.Handled = True
End If
End Sub
But for an email field how would I go about protecting against SQL injection for that textbox, as some email accounts have periods or dashes in them?
Update:
Below is an example of an insert statement I use.
Dim con As SqlConnection
con = New SqlConnection()
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=" & Server & ";Initial Catalog=" & Database & ";User ID=" & User & ";Password=" & Password & ";"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO TB_User(STRUserID, password, Email) VALUES('" & UsernameTextBox.Text & "', '" & MD5Hash(PasswordTextBox.Text) & "', '" & EmailTextBox.Text & "')"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
So I need to run this with parametrized queries rather than how I'm doing it now?
Instead of filtering out "invalid" data from user input, consider using parametrized queries and not putting user input directly into your queries; that's very bad form.
To run your current query using parameters, it's pretty easy:
Dim con As New SqlConnection()
Dim cmd As New SqlCommand()
Try
con.ConnectionString = "Data Source=" & Server & ";Initial Catalog=" & Database & ";User ID=" & User & ";Password=" & Password & ";"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO TB_User(STRUserID, password, Email) VALUES(#username, #password, #email)"
cmd.Parameters.Add("#username", SqlDbType.VarChar, 50).Value = UsernameTextBox.Text
cmd.Parameters.Add("#password", SqlDbType.Char, 32).Value = MD5Hash(PasswordTextBox.Text)
cmd.Parameters.Add("#email", SqlDbType.VarChar, 50).Value = EmailTextBox.Text
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
All you have to do is use cmd.Parameters.Add with a parameter name and the right database type (the ones I guessed probably don't match up, so you'll want to change them), then set the value to the value you want used in the query. Parameter names start with an #.
It doesn't depend on the textbox. Don't compose a sql sentence joining strings like this:
"SELECT * FROM User WHERE UserName=" + tbName.Text + ...
Use stored procedures or parameterized queries and you'll be safe from SQL injection.
When you use parameters, the textbox content is used as a value, so it doesn't matter what it contains.
Use a parametrized query like this:
Using conn = New SqlConnection("some connection string")
Using cmd = New SqlCommand("SELECT Password FROM tblUser WHERE UserName = #Name", conn)
cmd.Parameters.Add(New SqlParameter("Name", UsernameTextBox.Text))
conn.Open()
Dim password As String = DirectCast(cmd.ExecuteScalar(), String)
Console.WriteLine(password)
End Using
End Using
This is injection safe!