i am trying to update MS-Access database table with the code below using VB.net and i get this Error "Syntax error in UPDATE statement"
Dim Dcon As OleDbConnection
Dim Dcom As OleDbCommand
Dcon = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " & DataSource & ";")
Dcom = New OleDbCommand("UPDATE Drivers SET ID=?,First=?,Last=?,Company=?,Addr=?,City=?,ST=?,Zip=?,MobileP=?,HomeP=?,Email=?,DL=?,DateSince=?,DateTerm=?,TruckID=?,Commants=?,Image=? WHERE ID = ID=?", Dcon)
Dcom.Parameters.AddWithValue("#ID", Label3.Text)
Dcom.Parameters.AddWithValue("#First", TextBox1.Text)
Dcom.Parameters.AddWithValue("#Last", TextBox2.Text)
Dcom.Parameters.AddWithValue("#Company", TextBox3.Text)
Dcom.Parameters.AddWithValue("#Addr", TextBox4.Text)
Dcom.Parameters.AddWithValue("#City", TextBox5.Text)
Dcom.Parameters.AddWithValue("#ST", TextBox6.Text)
Dcom.Parameters.AddWithValue("#Zip", TextBox7.Text)
Dcom.Parameters.AddWithValue("#MobileP", TextBox8.Text)
Dcom.Parameters.AddWithValue("#HomeP", TextBox9.Text)
Dcom.Parameters.AddWithValue("#Email", TextBox10.Text)
Dcom.Parameters.AddWithValue("#DL", TextBox11.Text)
Dcom.Parameters.AddWithValue("#DateSince", TextBox12.Text)
Dcom.Parameters.AddWithValue("#DateTerm", TextBox13.Text)
Dcom.Parameters.AddWithValue("#TruckID", TextBox14.Text)
Dcom.Parameters.AddWithValue("#Commants", TextBox15.Text)
Dcom.Parameters.AddWithValue("#Image", DriverImage)
Dcom.Parameters.AddWithValue("#ID", Label3.Text)
Dcom.ExecuteNonQuery()
Dcon.Close()
I spent hours on google and i am unable to resolve this issue
this are my Field name
ID, First, Last, Company, Addr, City, ST, Zip, MobileP, HomeP, Email, DL, DateSince, DateTerm, TruckID, Commants, Image they all TEXT
Can anyone could tell me what is wrong with this syntax
The words FIRST and IMAGE are reserved keywords in MS-Access Jet SQL. If you want to use them you should use square brackets around them.
Also the syntax for the where clause is wrong. (But this is probably just a typo)
Dcom = New OleDbCommand("UPDATE Drivers SET " +
"ID=?,[First]=?,Last=?,Company=?,Addr=?,City=?," +
"ST=?,Zip=?,MobileP=?,HomeP=?,Email=?,DL=?,DateSince=?," +
"DateTerm=?,TruckID=?,Commants=?,[Image]=? WHERE ID=?", Dcon)
There is a syntax problem at the end of your sql query:
... WHERE ID = ID=?
I assume that should be
WHERE ID = ?
You're adding the ID parameter to your parameter list twice, once at the beginning and end.
Dcom.Parameters.AddWithValue("#ID", Label3.Text)
...
Dcom.Parameters.AddWithValue("#ID", Label3.Text)
Get rid of one of them.
Related
I want to insert data into MS Access database (mdb) table. The code is shown below:
Imports System.Data.OleDb
Imports System.Data
Dim Cmd As OleDbCommand
Dim SQL As String
Dim objCmd As New OleDbCommand
Dim Con = New OleDbConnection("Provider=Microsoft.ace.oledb.12.0; Data Source=" & pth & "\database.mdb; User Id=; Password=;")
MsgBox(RichTextBox1.SelectedText)
SQL = "insert into approved ( word, approveds) VALUES ('" & RichTextBox1.SelectedText & "', " & "'YES')"
MsgBox(SQL)
Cmd = New OleDbCommand(SQL, Con)
Con.Open()
objCmd = New OleDbCommand(SQL, Con)
objCmd.ExecuteNonQuery()
Con.Close()
It shows following error message
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Data type mismatch in criteria expression.
Can any one please help
Or any other procedure
First thing's first.
What do you expect " & "'YES' to mean ? Correct me if i'm wrong but you want to pass Yes as the value ? Or maybe even "Yes"(with quotes) ?
If it's the first one, only Yes inside single quotes would be enough('Yes'). For the second case, it would be '\"Yes\"'.
There are still too many issues with your code. You are using & operator to concatenate strings. Some might argue that there's no problem with using & but look at the code and tell me what's your first expression? Well, my first expression was :
That looks ugly!
So, instead of concatenation, you could simply format the string. Of course the results are the same, yet string formatting would look cleaner and more professional. Here's a sample :
Dim x as String = "My Name Is {0}."
Dim MyName As String = String.Format(x, "Zack Raiyan")
Now comes MsgBox(SQL). Well, i don't need a second guess for this, you are using this line to see if your sql statement is as expected. If that's the case, why not just put a breakpoint ?
Now, let's talk about your variable declarations. Why declare a variable without initializing it with any instance but later on, just after a few lines of code, initialize it when this could've been done in the first place ? Sample :
Dim x As New ObjectX
Instead of
Dim x As Object
.....
.....
x = New Object()
Finally, if you are getting to frustrated reading all these suggestions, let's talk about the main culprit here, your sql statement.
insert into approved ( word, approveds)
A space before and after the parenthesis may not make any difference but why use them at all? You may be new in programming but understand this:
You would spend 20% of your time in writing code and 80% of your time in maintaining it.
So, always write clean, simple & reusable codes.
Moving on....
VALUES ('" & RichTextBox1.SelectedText & "')
Don't do this! Instead pass parameters and then pass values to them. A quick example :
Dim sql = New SqlCommand("Insert Into TableX(Column1)Values(#Column1Val)", MySqlConnection)
sql.Parameters.Add("#Column1Val", SqlDbType.VarChar).Value = "XYZ"
There's a shorter way tho :
sql.Parameters.AddWithValue("#Column1Val", "XYZ")
but only use it when you know that you are passing a value of the same data type as the column you are passing it to.
I explained as much i could. I hope you understand your mistakes and also hope that you don't fail to see how my answer addresses the exception you are getting. If you are still unclear, leave a comment and i would be happy to help.
Just a small addition to #zack raiyan 's code. That is the Using block which will close and dispose your connection. This is important with connection objects because they use unmanaged code.
I am guessing that since your error is a data type mismatch that the problem might be with the approveds column. If this is a Yes/No column then it should be safe to use True for the value.
Check the data types of the 2 parameters in your database table and adjust the code appropriately.
Private Sub AddRecord(pth As String)
Dim SQL = "insert into approved ( word, approveds) VALUES (#word, #approval)"
Using Con As New OleDbConnection("Provider=Microsoft.ace.oledb.12.0; Data Source=" & pth & "\database.mdb; User Id=; Password=;")
Dim Cmd As New OleDbCommand(SQL, Con)
Cmd.Parameters.Add("#word", OleDb.OleDbType.VarChar).Value = RichTextBox1.SelectedText
Cmd.Parameters.Add("#approval", OleDbType.Boolean).Value = True
Con.Open()
Cmd.ExecuteNonQuery()
End Using
End Sub
JUST A HEADS UP ----- This no longer applies for me. I fixed it by adding the following two lines to my form.load.
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
It has fixed the issue for me and I hope it sorts it out for you too.
Okay, so, I have an application in VB.net that serves as a scheduler for the trainers at the company I work at. In the edit mode (so updates can be made to the database the information is stored on) there are a number of buttons, adding and removing trainers, or adding weeks to the table.
The button causing me problems is the save/update button. It has three sets of commands within it, one for updating added columns, one for removed columns, and then a third one which simply updates other modified data. I know it probably could be more efficient but oh well, I'll get to that later.
The problem is, the last chunk of code includes "da.update(ds)" which is the data adapter updating the datasource. While this command works perfectly fine in our other app that connects to our SQL server, its causing problems here.
Any column where the first cell's value is null causes an exception saying
"Incorrect syntax near 'the column header's first two characters'."
Now, I thought this issue stemmed from - due to the exception - me using an incorrect set of names for the columns, which were the dates of the mondays of each week (so for example 01/02/2016) so it'd show Incorrect syntax near '01'. in this instance.
However, changing the naming convention did not fix this like how the exception would suggest, and it only occurs on columns where the FIRST value is a null - implying that the first trainer has nothing planned for this week right now.
Anyone have any ideas as to a way around this that doesnt involve basically filling in every null on this rather large table? I know that would work but It'd be pretty time consuming, and I am willing to do this if no other solution rears its head.
I've looked around on the internet and haven't found a solution that appeared relevant to our exact issue, so help would be very appreciated.
In case it is important - here is the function causing the issue.
Dim da As OleDbDataAdapter 'The datasets and adapters variables.
Dim da2 As OleDbDataAdapter
Public ds As DataSet = New DataSet
Public ds2 As DataSet = New DataSet
'Connection String. Connects to the server and finds the database and table listed.
cs = "Provider=SQLOLEDB;"
cs &= "Server=SOFWAREDEVSQLSE\SQLEXPRESS;"
cs &= "Database=MTS2;"
cs &= "User Id=;" 'You don't need to see that to be fair.
cs &= "Password=;" 'You don't need to see that to be fair.
sql = "Select * FROM MTS2;"
'Runs the string. Flares up a timed out error if connection could not be established.
Try
da = New OleDbDataAdapter(sql, cs)
da.Fill(ds)
da2 = New OleDbDataAdapter(sql, cs)
da2.Fill(ds2)
Catch ex As Exception
MsgBox("Connection failed. Please ensure you have a suitable connection to the Training network. Otherwise, refer to helpdesk support for further assistance.")
Me.Close()
End Try
dgvSchedule.DataSource = ds.Tables(0)
Private Function save()
'Try
''This section reads the SQL server for column names, and adds any that are listed in the DGV, but not the database. I know its a little messy but itll do.
Dim columnnum As Integer = -1
Dim columname As String
For Each column In ds.Tables(0).Columns
columnnum = columnnum + 1
columname = dgvSchedule.Columns(columnnum).HeaderText
If Not ds2.Tables(0).Columns.Contains(columname) Then
Dim SqlAddCol As String = "ALTER TABLE MTS2 ADD [" & columname.Trim() & "] nvarchar(255)"
Using con As New OleDbConnection(cs)
Using cmd As New OleDbCommand(SqlAddCol, con)
con.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End If
Next
columnnum = -1
For Each column In ds2.Tables(0).Columns
columnnum = columnnum + 1
columname = ds2.Tables(0).Columns(columnnum).ColumnName
If Not ds.Tables(0).Columns.Contains(columname) Then
Dim SqlDelCol As String = "ALTER TABLE MTS2 DROP COLUMN [" & columname.Trim() & "]"
Using con As New OleDbConnection(cs)
Using cmd As New OleDbCommand(SqlDelCol, con)
con.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End If
Next
ds2.Tables.Clear()
da2 = New OleDbDataAdapter(sql, cs)
da2.Fill(ds2)
da.Update(ds) ''''' The exception is thrown here. " Incorrect syntax near '01'."
DataTableColours()
MessageBox.Show("Data saved successfully. New weeks and trainers added and deleted. Changed values updated.")
'Catch
' MessageBox.Show("Data failed to update properly. Please ensure you are connected to the Baltic network and try again. If the problem persists, seek IT support.")
'End Try
End Function
The function saves the values in the data grid view (DGVSchedule) to the server by taking the current columns in the DS with their original columns (which are in DS2) A Sql query is then ran to add or remove any column mismatches. DS2 is then updated to use the same values as DS. Finally, DA.update(DS) is called, which updates all other modified values into the SQL server - theoretically. It is instead causing our peculiar exception.
Any help would be greatly appreciated, thanks.
I have fixed the problem I was encountering. I fixed it by adding the following two lines to my form.load.
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
Basically, I feel like a dumbass now but this solved the problem.
I am a Student and ASP is my subject this year. I am trying to do the Database Connectivity for the First time. It gave me this Error while i was connecting my ASP file with MSAccess.
Code:
<%
Dim objConn, strConn, objRS
Set objConn = Server.CreateObject("ADODB.Connection")
strConn = "PROVIDER=Microsoft.ACE.OLEDB.12.0;DATA SOURCE =" & _
"C:\demo.accdb"
objConn.Open strConn
Set objRS = Server.CreateObject("ADODB.Recordset")
objRS.Open "Student", objConn, 2, 2
objRS.AddNew
objRS("idnum") = Request.Form("idnum")
objRS("firstname") = Request.Form("firstname")
objRS("lastname") = Request.Form("lastname")
objRS.Update
objRS.close
%>
**The Above code Gives the Following Error:*
ADODB.Recordset error '800a0cc1'
Item cannot be found in the collection corresponding to the requested name or ordinal.
/MyWeb/choice1.asp, line 12*
.. I also tried doing this..
..
..
Dim objConn, strConn, objRS
Set objConn = Server.CreateObject("ADODB.Connection")
strConn = "DSN=Stud"
objConn.Open strConn
and it gives me the same error.
My Database name is demo.accdb
My Table name is Student.
ApplicationPool Settings for IIS is set to "true" for using Windows 32bit.
I have also installed OLEDB ACE 12.
Please help as am totally in mess.. All I want is to insert a record in an Access Database.
Help would be appreciated.
That error has nothing to do with your connection, setup, IIS settings, or anything esoteric, and everything to do with what columns exist (or rather, don't exist) in the recordset you're opening.
What is in line 12 of your code? (In the snippet you've posted, line 12 is the "lastname" field, but I don't know if that's true for your actual code.) Check the setup of the Student table: did you spell that column name correctly? If the table column is LastN, then your code should have objRS("LastN") = Request.Form("LastName")1, not objRS("LastName").... Thankfully, neither VBScript nor SQL are case-sensitive, so you don't need to be anal, but you do need to spell things correctly.
Note that it may help you "see" what you're doing better if you write an explicit SELECT statement to return just the columns (and rows) you want, instead of opening the entire table. Also, when you're working with actual databases (which tend to have many thousands or even millions of records, rather than the half a dozen you probably have in your test database), opening entire tables is A Very Bad Idea. Well, unless you like timeout errors.
objRS.Open "SELECT TOP 0 id, firstname, lastname FROM Student", objConn, 2, 2
(Since all you're doing is adding a row, you don't actually need to return any records; hence the TOP 0.2)
1 All you "OMG! Your code is vulnerable to SQL injection!!1!" types can insert your customary rant here.
2 It's been a while since I've worked with Access; if it chokes on TOP 0 with no ORDER BY clause, try SELECT ... WHERE 1 = 2.
I had confusion with my code:
Dim sqladapter As SqlDataAdapter = New SqlDataAdapter()
Dim sqlcmd As SqlCommand = New SqlCommand()
sqlcmd = New SqlCommand("SELECT login, pass from Table1 where login=" & login.Text & "and pass='" & password.Text.ToString() & "';", connect)
Dim dr As SqlDataReader = sqlcmd.ExecuteReader()
Dim dt As DataTable = New DataTable()
dt.Load(dr)
If (dt.Rows.Count = 1) Then
'Display welcome page or do some action here.
Now, my question is, is there any other way of doing Rows.Count==1 . I'm feeling that it is very wrong and makes no sense at.
How do you verify from database that a user has only one valid record in table other than counting rows.
Thanks in Advance :)
(Please ask me before reporting question)
You have two problems, one is called Sql Injection and you have already numerous links that explain why is really bad. Another one is the plain text password stored in your database. This is a big security concern because everyone that has the possibility to look at your database could see the passwords of your users. (The gravity of this, of course, is linked to the nature of your application but cannot be downplayed) See this link for an answer on how to hash a string (a password) and get its encrypted version to store in the database instead of the plain text.
Finally the code you use could be changed to avoid both the SqlDataAdapter and the DataTable.
Just use an ExecuteScalar against an IF EXIST query that return just 1 if the user/password exists or zero if not
Dim cmdText = "IF EXISTS(SELECT 1 FROM Table1 WHERE login = #log AND pass = #pwd) " & _
"SELECT 1 ELSE SELECT 0"
using connect = new SqlConnection(connectionstring)
using sqlcmd = New SqlCommand(cmdText, connect)
connect.Open()
sqlcmd.Parameters.AddWithValue("#log", login.Text)
sqlcmd.Parameters.AddWithValue("#pwd", password.Text) ' <- Subst with a call to an hash function
Dim exists = Convert.ToInt32(sqlcmd.ExecuteScalar())
if exists = 1 Then
'Display welcome page or do some action
else
end if
End Using
End Using
There is only one way to answer to the question and its to count rows. The different solution would be to count them in database. For example you could write stored procedure that takes username and password and returns boolean this way you would drag less data.
As a side note there is potential sql injection in your code. You should not store clear password in database. You should return the whole row and match hash of the password from database to the hash of the paasword that you get from UI.
`Dim con1 As New ADODB.Connection
Dim rs1 As New ADODB.Recordset
Dim sql1 As String
sql1 = "Update Balance set Balance_Amt = (Balance_Amt + " & a & ") where Company = " & Combo3.Text
con1.Execute (sql1)
"Can anyone say why this code does not work? It says No value for one or more required parameters"
I would guess that the immediate problem is that the SQL fragment
where Company = value
is invalid SQL. It should be quoted:
where Company = 'value'
But you really should be using SQL parameters.
I would have avoided this issue since the parameter would have been automatically quoted as necessary.
It would have made the code easier to read.
It would not be susceptible to SQL Injection attacks.
e.g.
Using cmd = new SqlCommand("UPDATE Balance SET Balance_Amt = (Balance_Amt + #a) WHERE Company=#company", con1)
cmd.Parameters.AddWithValue("#a", a)
cmd.Parameters.AddWithValue("#company", company)
cmd.ExecuteNonQuery()
End Using
Print out the sql statement and see if it is ok, copy/paste it to the sql management studio.
I think you are missing apostrophes around the string Combo3.Text.
Also consider what sql it would result in if Combo3.Text contains
'a'; delete from Balance