Error on .ExecuteNonQuery() in SQL Update Query [duplicate] - sql

This question already has an answer here:
ADD SQL QUERY STAT
(1 answer)
Closed 8 years ago.
I'm trying to update an Access database using a SQL query, whenever I click the save button, it generates an error
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: No value given for one or more required parameters.
And highlights .ExecuteNonQuery(). Can you guys help me on this? I'm new to vb.net.
Thanks in advance.
Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
Dim empNum As String
Dim empFname As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
Dim empYears As String
empNum = eNumText.Text
empFname = empFnameText.Text
empLname = empLnameText.Text
empDept = DeptText.Text
empStat = StatText.Text
empYears = yearstext.Text
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
con.Open()
MsgBox(empNum)
Dim SqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
Dim sqlQuery As String = "UPDATE tbl_empinfo SET EmpID='" & empNum & "', FirstName ='" & empFname & "', LastName='" & empLname & "', Department='" & empDept & "', Status='" & empStat & "', Years='" & empYears & "' WHERE EmpID ='" & empNum & "' "
Using cmd As New OleDbCommand(sqlQuery, con)
With cmd
.CommandText = sqlQuery
.Connection = con
.Parameters.AddWithValue("EmpID", empNum)
.Parameters.AddWithValue("FirstName", empFname)
.Parameters.AddWithValue("LastName", empLname)
.Parameters.AddWithValue("Department", empDept)
.Parameters.AddWithValue("Status", empStat)
.Parameters.AddWithValue("Years", empYears)
.ExecuteNonQuery()
End With
End Using
sqlQuery = "SELECT * FROM tbl_empinfo "
Dim cmd1 As New OleDbCommand
Dim da As New OleDbDataAdapter
With cmd1
.CommandText = sqlQuery
.Connection = con
With SqlAdapter
.SelectCommand = cmd1
.Fill(Table)
End With
With DataGridView1
.DataSource = Table
End With
End With
con.Close()
End Sub

your query syntax is wrong. Since you are using params, use placeholders in the SQL: (the question marks are not some 'etc' type thing, you use ? to mark parameters!):
Dim sqlQuery As String = "UPDATE tbl_empinfo SET FirstName = ?,
LastName=?, Department=?,
Status=?, Years=? WHERE empID = ?"
Note: Six parameters
' USING will dispose of the cmd when it is done with it
' ...can also set the SQL and connection props in the constructor:
Using cmd As New OleDbCommand(sqlQuery, con)
With cmd
' no reason to move Textboxes to a variable either:
.Parameters.AddWithValue("#p1", empFnameText.Text)
.Parameters.AddWithValue("#p2", empLnameText.Text)
.Parameters.AddWithValue("#p3", DeptText.Text)
.Parameters.AddWithValue("#p4", StatText.Text)
.Parameters.AddWithValue("#p5", yearstext.Text)
your missing 6th parameter:
.Parameters.AddWithValue("#p6", eNumText.Text)
.ExecuteNonQuery()
End With
End Using
I dont think Access supports named params, so you use dummy ones but be sure to AddWithValue in the order specified in the SQL string.
EDIT
You can just create a SQL string with the values embedded instead of using params which is sort of what your SQL string does. Params are much better (research SQL injection attacks), but your string method is wrong (and you cant mix methods). It should be:
Dim sqlQuery As String = "UPDATE tbl_empinfo " &
"SET FirstName = " & empFname & ", LastName=" & empLname
The variables have to be outside the quotes or you will be setting FirstName to the literal "empFname"

Related

VB.net insert into error [duplicate]

This question already has an answer here:
Syntax error in INSERT INTO Statement when writing to Access
(1 answer)
Closed 7 years ago.
I'm using Microsoft Visual Studio 2013 and im trying to make a registration form for my account database using VB.NET. This is my code so far:
Private Sub btnRegistery_Click(sender As Object, e As EventArgs) Handles btnRegistery.Click
Dim usernme, passwrd As String
usernme = txtUsernm.Text
passwrd = txtpasswrd.Text
Dim myconnection As OleDbConnection
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\hasan\Documents\Visual Studio 2012\Projects\hasan\Login_Info.accdb"
myconnection = New OleDbConnection(constring)
myconnection.Open()
Dim sqlQry As String
sqlQry = "INSERT INTO tbl_user(username, password) VALUES(usernme , passwrd)"
Dim cmd As New OleDbCommand(sqlQry, myconnection)
cmd.ExecuteNonQuery()
End Sub
The code compiles fine, but when i try to register any new information i get the following message:
A first chance exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll
Additional information: Syntax error in INSERT INTO statement.
If there is a handler for this exception, the program may be safely continued.
What could be a solution and cause for this problem?
Your query seems wrong: ... VALUES(usernme, passwrd)... --
Here the usernmeand passwrd are not variables for database, but just plain text in the query.
Use parameters, like this:
Dim usernme, passwrd As String
usernme = txtUsernm.Text
passwrd = txtpasswrd.Text
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\hasan\Documents\Visual Studio 2012\Projects\hasan\Login_Info.accdb"
Using myconnection As New OleDbConnection(constring)
myconnection.Open()
Dim sqlQry As String = "INSERT INTO [tbl_user] ([username], [password]) VALUES (#usernme, #passwrd)"
Using cmd As New OleDbCommand(sqlQry, myconnection)
cmd.Parameters.AddWithValue("#usernme", usernme)
cmd.Parameters.AddWithValue("#passwrd", passwrd)
cmd.ExecuteNonQuery()
End using
End using
You aren't including the actual variable information missing the quotations, like
VALUES ('" & usernme & '", ...etc
You should be using parameters to avoid errors and sql injection:
sqlQry = "INSERT INTO tbl_user (username, password) VALUES(#usernme, #passwrd)"
Dim cmd As New OleDbCommand(sqlQry, myconnection)
cmd.Parameters.AddWithValue("#usernme", usernme)
cmd.Parameters.AddWithValue("#passwrd", passwrd)
cmd.ExecuteNonQuery()
Dim cnn As New OleDb.OleDbConnection
Private Sub RefreshData()
If Not cnn.State = ConnectionState.Open Then
'-------------open connection-----------
cnn.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("select stdID as [StdIdTxt]," &
"Fname as [FnameTxt] ,Lname,BDy,age,gender,address,email,LNO,MNO,course" &
"from studentTB order by stdID", cnn)
Dim dt As New DataTable
'------------fill data to data table------------
da.Fill(dt)
'close connection
cnn.Close()
End Sub
Private Sub AddNewBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddNewBtn.Click
Dim cmd As New OleDb.OleDbCommand
'--------------open connection if not yet open---------------
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
'----------------add data to student table------------------
cmd.CommandText = "insert into studentTB (stdID,Fname,Lname,BDy,age,gender,address,email,LNO,MNO,course)" &
"values (" & Me.StdIdTxt.Text & "','" & Me.FnameTxt.Text & "','" & Me.LNameTxt.Text & "','" &
Me.BdyTxt.Text & "','" & Me.AgeTxt.Text & "','" & Me.GenderTxt.Text & "','" &
Me.AddTxt.Text & "','" & Me.EmailTxt.Text & "','" & Me.Hometxt.Text & "','" & Me.mobileTxt.Text & "','" & Me.Coursetxt.Text & "')"
cmd.ExecuteNonQuery()
'---------refresh data in list----------------
'RefreshData()
'-------------close connection---------------------
cnn.Close()
This insert error is nothing but a syntax error, there is no need for changing your code. please avoid reserved words like "password" form your database. This error is due to the field name password
The SQL string should look like this
sqlQry = "INSERT INTO tbl_user(username, password) VALUES(" & usernme & "', " & passwrd & ")"
The values usernme & passwrd aren't valid to the database.
Beyond that you really should look into using a Command object and parameters.

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!

Search between two dates in access database using sql

This is my code for search in access database 2010. My problem is that when I search between two datetimepicker the result is wrong in datagridview, I mean when I search from specific records between May and June it shows me records also from February.
Private Sub Search_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Dim bookdetials As New frmContactDetails
Try
'get connection string declared in the Module1.vb and assing it to conn variable
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT contact_id, first_name , birth_date, book_num, send_from, no_answer, no_answer_by, rec, book_answer_name, book_answer_num, send_date, send_to, project_name FROM tblAddressBook"
If CheckBox1.Checked = True Then
sSQL = sSQL & " where project_name like '%" & Me.TextBox2.Text & "%' " & _
" AND birth_date between '" & DateTimePicker1.Text & "' AND '" & DateTimePicker2.Text & "'"
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
Label4.Text = dt.Rows.Count
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
datepicker text should be converted to datetime format in sql
I had the same problem, the solution was too silly but it worked
use text instead of datetime in the db
make sure the datetimepicker enters "short format" data

ADD SQL QUERY STAT

I'm trying to update the records from textboxes into the Access database, I'm wondering every time I hit save, it generates an error
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: No value given for one or more required parameters.
Highlighting .ExecuteNonQuery()
What does it mean? It's preventing me to run my code :(
Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
Dim empNum As String
Dim empFname As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
Dim empYears As String
empNum = eNumText.Text
empFname = empFnameText.Text
empLname = empLnameText.Text
empDept = DeptText.Text
empStat = StatText.Text
empYears = yearstext.Text
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
con.Open()
Dim SqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
Dim sqlQuery As String = "UPDATE tbl_empinfo " & _
"SET FirstName=empFname, LastName=empLname, Department=empDept, " & _
"Status=empStat, Years=empYears " & _
"WHERE empID=empNum"
Dim cmd As New OleDbCommand
With cmd
.CommandText = sqlQuery
.Connection = con
.Parameters.AddWithValue("FirstName", empFname)
.Parameters.AddWithValue("LastName", empLname)
.Parameters.AddWithValue("Department", empDept)
.Parameters.AddWithValue("Status", empStat)
.Parameters.AddWithValue("Years", empYears)
.ExecuteNonQuery()
End With
Using cmd2 = New OleDbCommand(sqlQuery, con)
cmd.Parameters.AddWithValue("FirstName", empFname)
cmd.Parameters.AddWithValue("LastName", empLname)
cmd.Parameters.AddWithValue("Department", empDept)
cmd.Parameters.AddWithValue("Status", empStat)
cmd.Parameters.AddWithValue("Years", empYears)
cmd.ExecuteNonQuery()
End Using
sqlQuery = "SELECT * FROM tbl_empinfo "
Dim cmd1 As New OleDbCommand
Dim da As New OleDbDataAdapter
With cmd1
.CommandText = sqlQuery
.Connection = con
With SqlAdapter
.SelectCommand = cmd1
.Fill(Table)
End With
With DataGridView1
.DataSource = Table
End With
End With
con.Close()
End Sub
You are trying to set an UPDATE command text for the SelectCommand of the Adapter. This, of course has no way to be successful. Last but not least the UPDATE command text doesn't contain a WHERE clause, and so, if executed, it updates every record in the table tbl_empinfo with the same data.
In this context there is no need to use an adapter. You could simply execute the command, providing an appropriate WHERE clause and the values for the other parameters
Dim sqlQuery As String = "UPDATE tbl_empinfo " & _
"SET FirstName=?, LastName=?, Department=?, " & _
"Status=?, Years=? " & _
"WHERE empID=?"
Dim cmd As New OleDbCommand
With cmd
.CommandText = sqlQuery
.Connection = con
.Parameters.AddWithValue("#p1", empFName)
.Parameters.AddWithValue("#p2", empLName)
.Parameters.AddWithValue("#p3", empDept)
.Parameters.AddWithValue("#p4", empStat)
.Parameters.AddWithValue("#p5", empYears)
.Parameters.AddWithValue("#p6", empNum)
.ExecuteNonQuery()
End With
After this you could call the code that reloads the data to fill your grid
sqlQuery = "SELECT * FROM tbl_empinfo"
Dim cmd1 As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim Table As New DataTable
With cmd1
.CommandText = sqlQuery
.Connection = con
With da
.SelectCommand = cmd1
.Fill(Table)
End With
With DataGridView1
.DataSource = Table
End With
End With
Notice that I have changed the name of the command and the adapter to a less confusing names. SqlCommand And SqlDataAdapter are the names of the classes equivalent to the OleDbCommand and OleDbDataAdapter but used for Sql Server. At first sight I was thinking that you were trying to use the SqlClient classes to update an MS-Access database.

VB.NET SQL ACCESS Insert Statement

net and i'm trying to insert data into access database using sql, i have the code below, when i try to execute, it prompts me an error message and highlighting con.open() i don't understand why it's not working, can anyone guide me. Thank
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles AddBut.Click
Dim dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
Dim dbSource = "Data Source= C:\Databse\Company_db.accdb"
Dim empNum As String
Dim empFname As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
Dim empYears As String
empNum = eNumText.Text
empFname = empFnameText.Text
empLname = empLnameText.Text
empDept = Deptd.Text
empStat = Statd.Text
empYears = yearstext.Text
Dim sql = "INSERT INTO tbl_empinfo (EmpID, FirstName, LastName, Department, Status, Years " & _
") " & _
"Values(empNum, empFname, empLname, empDept, empStat, empYears)"
con.ConnectionString = dbProvider & dbSource
Using cmd = New OleDb.OleDbCommand(sql, con)
con.Open()
cmd.Parameters.AddWithValue("EmpID", empNum)
cmd.Parameters.AddWithValue("FirstName", empFname)
cmd.Parameters.AddWithValue("LastName", empLname)
cmd.Parameters.AddWithValue("Department", empDept)
cmd.Parameters.AddWithValue("Status", empStat)
cmd.Parameters.AddWithValue("Years", empYears)
cmd.ExecuteNonQuery()
End Using
con.Close()
End Sub
Standard problem, when you see a Syntax error in an otherwise fine SQL statement, look for RESERVED KEYWORDS for the underlying database.
In your case the word POSITION is a reserved keyword for MS-ACCESS.
Put it between square brackets
Dim sql = "INSERT INTO tbl_empinfo (EmpID, FirstName, LastName, Department, " & _
"[Position], Status, Years) " & _
"Values(empNum, empFname, empLname, empDept, empStat, empYears)"
However, you have another error in that query. You have 7 fields to insert but you pass only 6 parameters, missing just the parameter for the POSITION field.
You need to fix also the connection string. You write
con.ConnectionString = dbProvider & dbSource
but this result in an invalid file name
"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=
c:\Databse\Company_db.accdbData Source= C:\Databse\Company_db.accdb"
(line splitted for readability)
I consider that you have initialized the object of "OleDbConnection".
Try to get the Connection String from the Property window of your database (From Server Explorer Window right click on your database select properties option).
And when you are opening the connection use following code:
If con.State = ConnectionState.Closed Then
con.Open()
End If
Hope it helps you.