No value given for one or more required parameters error vb.net - 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

Related

How to quick update MySQL table through a loop using VB.net

My code for updating mysql table having more than 2000 rows through a loop using VB.net is working fine but too slow. Is there any way to update it faster ? Anybody please help. Thanks. My code is given below.
Dim mysqlconn = New MySqlConnection
mysqlconn.ConnectionString = "server=localhost;user id=root;password=1234;database=Share"
mysqlconn.Open()
Dim adapter As New MySqlDataAdapter("SELECT * FROM name_list;", mysqlconn)
Dim datatable As New DataTable()
adapter.Fill(datatable)
Dim cmd As New MySqlCommand
cmd.Connection = mysqlconn
Dim sql As String
Dim i as integer = 0
While i <= datatable.Rows.Count - 1
Dim sy As String = datatable.Rows(i).Item(3).ToString.Trim
sql = "UPDATE Name_list Set Numerology = '" & "N-" & variable1 & " S- " & variable2 & "',FSTLetter = '" & variable3 & "',Timing = '" & vriable4 & "',P_Numerology = '" & variable5 & "' WHERE Symbol = '" & sy & "'"
sy = ""
cmd.CommandText = sql
cmd.ExecuteNonQuery()
i = i + 1
End While
adapter.Fill(datatable)
DataGridView1.DataSource = datatable
DataGridView1.Refresh()
Don't name variables the same as class names (DataTable, datatable) vb.net is case insensitive so it confuses intellisense.
Database connections and commands need to closed and disposed.
Using blocks do this for you even if there is an error.
You can set the connection string by passing it directly to the constructor of the connection. Likewise, you can set the command text and the connection by passing to the constructor of the command.
Don't open the connection until right before it is used. In this case we don't need a DataAdapter but if you are using one it is not necessary to open the connection at all. The .Fill method of the DataAdapter will open and close the connection. However if the DataAdapter finds an open connection it will leave it open.
To avoid confusion, I created 2 data tables. I used a single connection but I opened and closed it each time it is used. It is not disposed until the last End Using.
The first command retrieves only the sy column. Replace Column4_Name with the actual column name. We don't want to pull down data we don't need so no Select *.
Always use parameters to avoid sql injection which can damage your database. You need to check your database for the types of the fields. I had to guess. Each parameters value is set except sy which changes on each iteration.
No need to close the connection after the last Select command since the final End Using will close and dispose.
After the connection is closed we update the user interface.
Private Sub OPCode(variable1 As String, variable2 As String, variable3 As String, variable4 As String, variable5 As String)
Dim dtBeforeUpdate As New DataTable()
Dim dtAfterUpdate As New DataTable()
Using mysqlconn = New MySqlConnection("server=localhost;user id=root;password=1234;database=Share")
Using cmd As New MySqlCommand("SELECT Column4_Name FROM name_list;", mysqlconn)
mysqlconn.Open()
dtBeforeUpdate.Load(cmd.ExecuteReader)
mysqlconn.Close()
End Using
Using cmd As New MySqlCommand($"UPDATE Name_list Set Numerology = #Numerologh, FSTLetter = #FST, Timing = #Timing, P_Numerology = #P_Numerology WHERE Symbol = #sy ", mysqlconn)
cmd.Parameters.Add("#Numerology", MySqlDbType.String).Value = $"N-{variable1} S- {variable2}"
cmd.Parameters.Add("#FST", MySqlDbType.String).Value = variable3
cmd.Parameters.Add("#Timing", MySqlDbType.String).Value = variable4
cmd.Parameters.Add("#P_Numerology", MySqlDbType.String).Value = variable5
cmd.Parameters.Add("#sy", MySqlDbType.String)
mysqlconn.Open()
For Each row As DataRow In dtBeforeUpdate.Rows
cmd.Parameters("#sy").Value = row(0).ToString.Trim
cmd.ExecuteNonQuery()
Next
mysqlconn.Close()
End Using
Using cmd As New MySqlCommand("Select * From Name_list;", mysqlconn)
mysqlconn.Open()
dtAfterUpdate.Load(cmd.ExecuteReader)
End Using
End Using
DataGridView1.DataSource = dtAfterUpdate
End Sub
Actually, I don't get it. It seems like you are updated the entire table with the same data. Do you expect the variable1, variable2 etc. to change somehow?
Don't know where your variable1, variable2, etc come from, but those look to be static, so your loop is somewhat pointless it would seem. You're updating every row in the loop to the exact same values (unless there's other code you're not showing), so just update the table without the loop:
Using con As New MySQLConnection
con.ConnectionString = "server=localhost;user id=root;password=1234;database=Share"
con.Open
Using cmd As New MySQLCommand
cmd.Connection = con
cmd.CommandText = "UPDATE Name_list Set Numerology = '" & "N-" & variable1 & " S- " & variable2 & "',FSTLetter = '" & variable3 & "',Timing = '" & vriable4 & "',P_Numerology = '" & variable5 & "'"
cmd.ExecuteNonQuery
End Using
End Using

How do I read HasRow then Update?

Is it possible to read HasRow and then Update ?
This is the code what I have tried so far :
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlcmd As New MySqlCommand("SELECT * FROM tbl_online_attendance where employees_id = '" & lvRealAtt.Items(itms).SubItems(0).Text & "' and in_time = '" & lvRealAtt.Items(itms).SubItems(1).Text & "' ", conn)
Dim dr As MySqlDataReader
dr = sqlcmd.ExecuteReader
If dr.HasRows Then
Dim query As String
query = "UPDATE tbl_online_attendance SET out_time = '" & lvRealAtt.Items(itms).SubItems(2).Text & "' where employees_id = '" & lvRealAtt.Items(itms).SubItems(0).Text & "' and in_time = '" & lvRealAtt.Items(itms).SubItems(1).Text & "' "
sqlcmd.Connection = conn
sqlcmd.CommandText = query
sqlcmd.ExecuteNonQuery() 'It error in this part
Else
End If
But it give's me error saying:
There is already an open DataReader associated with this Connection which must be closed first
Please avoid commenting Use Parameters Your code is Prone to SQL injection attack
You should not have to check connection state if you keep your connections local to the method that they are used. Database objects like connections and commands need to be closed and disposed as soon as possible. Using...End Using blocks take care of this for you even if there is an error. Don't open a connection until directly before the .Execute....
Don't pull down data when you only need Count. .ExecuteScalar returns the first column of the first row of the result set, which in this case, is the Count. If you have a large table you need to look into If Exists which will stop as soon it finds a match whereas Count looks at the whole table.
Always use Parameters. Never concatenate strings to build sql queries to avoid sql injection. I had to guess at the datatypes of the parameters. Check your database to get the actual types and adjust the code accordingly.
Private Sub OPCode(ByVal itms As Integer)
Dim RowCount As Integer
Using conn As New MySqlConnection("Your connection string"),
sqlcmd As New MySqlCommand("SELECT Count(*) FROM tbl_online_attendance where employees_id = #id and in_time = #inTime;", conn)
sqlcmd.Parameters.Add("#id", MySqlDbType.Int32).Value = CInt(lvRealAtt.Items(itms).SubItems(0).Text)
sqlcmd.Parameters.Add("#inTime", MySqlDbType.String).Value = lvRealAtt.Items(itms).SubItems(1).Text
conn.Open()
RowCount = CInt(sqlcmd.ExecuteScalar)
If RowCount > 0 Then
sqlcmd.CommandText = "UPDATE tbl_online_attendance SET out_time = #outTime where employees_id = #id and in_time = #inTime;"
sqlcmd.Parameters.Add("#outTime", MySqlDbType.String).Value = lvRealAtt.Items(itms).SubItems(2).Text
sqlcmd.ExecuteNonQuery()
End If
End Using
End Sub
Every SqlDataReader needs to be closed before you could execute another query.
so i suggest you to separate the sqlreader and the update query, put the reader into a boolean function to check either a row with those parameters exist or not.
Private Function HasRow(ByVal employeeid As Integer, ByVal date as DateTime) As Boolean
HasRow = False
Dim reader As SqlDataReader
'do select query here
'use the if reader.Read if you want to
HasRow = reader.HasRows
reader.Close()
End Function
Call the function before updating, if it's True then proceed the update. Let's say we put it into a Update Sub.
Private Sub Update()
If HasRows(parameters here) Then
'update query here
End If
End Sub

Data type mismatch in criteria expression while updating password field

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.

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

Problems connecting to database in VB.NET

Dim con As New System.Data.SqlClient.SqlConnection
con.ConnectionString = "Server=iraq\\sqlexpress ; Database=stats ; Trusted_Connection=True ;"
Dim com As New System.Data.SqlClient.SqlCommand
com.CommandText = "insert into users values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "')"
com.Connection = con
con.Open()
com.ExecuteNonQuery()
con.Close ()
There are new events happen when i adjust the connection string
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\WebSite2\App_Data\stats.mdf;Integrated Security=True;User Instance=True"
show me error with com.ExecuteNonQuery()
any suggestion ?
Can't speak to your connection String. Looks rather arduous. Beyond that, I see a few problems:
A. This is the most obvious to me: Your INSERT statement is incorrect. Try THIS:
INSERT INTO your_table_name (column_name_1, column_name_2, . . .) VALUES (value_1, value_2, . . .)
B. Extend the above, in keeping with the comments of others, and properly PARAMETERIZE your query. Further, make use of the Application Settings file for your connection string, instead of hardcoding it into your app. Last, employ a Using block, for the connection and command objects - this will handle initialization and Disposal of these. I stripped the following out of an old project of mine - hopefully I didn't muff any sytax adapting it for this post. The original code ran against a Stored Procedure in the SQL Server back-end:
Public Overridable Sub DataINSERT() Implements IAppUser.DataINSERT 'tblAppUser
Dim CommandText As String = "INSERT INTO tblUser(UserName, PassWord, Enabled) VALUES(#UserName, #PassWord, #Active)"
'The Connection String can be established in your Project Settings file:
Using cn As New SqlClient.SqlConnection(My.Settings.MyDataConnectionString)
Using cmd As New SqlClient.SqlCommand(CommandText, cn)
cmd.CommandType = CommandType.Text
'INSERT PARAMETER SET_UP:
Dim prmUserName As New SqlClient.SqlParameter("#UserName", SqlDbType.VarChar, 50)
prmUserName.Direction = ParameterDirection.Input
prmUserName.Value = _UserName
cmd.Parameters.Add(prmUserName)
Dim prmPassWord As New SqlClient.SqlParameter("#PassWord", SqlDbType.VarChar, 50)
prmPassWord.Direction = ParameterDirection.Input
prmPassWord.Value = _PassWord
cmd.Parameters.Add(prmPassWord)
Dim prmActive As New SqlClient.SqlParameter("#Active", SqlDbType.Bit, 0)
prmActive.Direction = ParameterDirection.Input
prmActive.Value = _Active
cmd.Parameters.Add(prmActive)
Try
cn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Dim str As String = Me.ToString & ": " & ex.Message & " / " & ex.TargetSite.ToString
MsgBox(str)
End Try
End Using
End Using
End Sub 'DataINSERT tblAppUser
My final comment would be to check out Stored Procedures with SQL Server. Let me know if any of this doesn't make sense.