Why do I get "Syntax error in INSERT INTO statement"? - sql

Private Sub Save_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim sSQL As String = String.Empty
Try
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandText = CommandType.Text
If Me.txt_Forename.Tag = 0 Then
sSQL = "INSERT INTO PlayerDatabase ( Age_Group, Surname, Forename, Rating, DOB, Address, Email, Position, Foot, Mins_Played, Goals, Assists, Yellow_Cards, Red_Cards)"
sSQL = sSQL & " VALUES(#Age_Group, #Surname, #Forename, #Rating, #DOB, #Address, #Email, #Position, #Foot, #Mins_Played, #Goals, #Assists, #Yellow_Cards, #Red_Cards)"
Else
sSQL = "UPDATE PlayerDatabase set Age_Group = #Age_Group, Surname = #Surname, Forename = #Forename, Rating = #Rating, DOB = #DOB, Address = #Address, Email = #Email, Position = #Position, Foot = #Foot, Mins_Played = #Mins_Played, Goals = #Goals, Assists = #Assists, Yellow_Cards = #Yellow_Cards, Red_Cards = #Red_Cards WHERE ID = #id"
cmd.CommandText = sSQL
End If
cmd.Parameters.Add("#Surname", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txt_Surname.Text)) > 0, Me.txt_Surname.Text, DBNull.Value)
cmd.Parameters.Add("#Forename", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txt_Forename.Text)) > 0, Me.txt_Forename.Text, DBNull.Value)
cmd.Parameters.Add("#DOB", OleDbType.Date).Value = Me.dtp_DOB.Text
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = Me.txt_Address.Text
cmd.Parameters.Add("#Age_Group", OleDbType.VarChar).Value = Me.cb_AgeGroup.Text
cmd.Parameters.Add("#Rating", OleDbType.VarChar).Value = Me.cb_Rating.Text
cmd.Parameters.Add("#Email", OleDbType.VarChar).Value = Me.txt_Email.Text
cmd.Parameters.Add("#Position", OleDbType.VarChar).Value = Me.cb_Position.Text
cmd.Parameters.Add("#Foot", OleDbType.VarChar).Value = Me.cb_Foot.Text
cmd.Parameters.Add("#Mins_Played", OleDbType.VarChar).Value = Me.nup_MinsPlayed.Text
cmd.Parameters.Add("#Goals", OleDbType.VarChar).Value = Me.nup_Goals.Text
cmd.Parameters.Add("#Assists", OleDbType.VarChar).Value = Me.nup_Assists.Text
cmd.Parameters.Add("#Yellow_Cards", OleDbType.VarChar).Value = Me.nup_YellowCards.Text
cmd.Parameters.Add("#Red_Cards", OleDbType.VarChar).Value = Me.nup_RedCards.Text
cmd.Parameters.Add("#ID", OleDbType.Numeric).Value = Me.txt_Forename.Tag
cmd.ExecuteNonQuery()
If Me.txt_Forename.Tag = 0 Then
cmd.CommandText = "Select ##Identity"
Me.txt_Forename.Tag = cmd.ExecuteScalar()
End If
MsgBox("Data has been saved.")
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
Not sure what I'm doing wrong here. This is a adding to an Access database from various textboxes, comboboxes etc. This procedure runs when a button is pressed on a form that has the inputs. I'm a beginner at vb.net and programming in general so if it's something obvious I apologise.
Thanks

The word POSITION is reserved in MS-Access Jet Sql. This is the reason of the SYNTAX ERROR.
If you want to use it as a name for a column or for a table you need to put it between square brackets
sSQL = "INSERT INTO PlayerDatabase ( Age_Group, Surname, Forename, Rating, DOB, " & _
"Address, Email, [Position], Foot, Mins_Played, Goals, Assists, Yellow_Cards, Red_Cards)"
....
sSQL = "UPDATE PlayerDatabase set Age_Group = #Age_Group, Surname = #Surname, " & _
"Forename = #Forename, Rating = #Rating, DOB = #DOB, Address = #Address, " & _
"Email = #Email, [Position] = #Position, Foot = #Foot, Mins_Played = #Mins_Played, " & _
"Goals = #Goals, Assists = #Assists, Yellow_Cards = #Yellow_Cards, " & _
"Red_Cards = #Red_Cards WHERE ID = #id"
A part from this you have another problem. OleDb doesn't recognize the parameters by their names. Usually you should use a question mark instead of a name, but Access allows this probably for some kind of portability toward its big cousin Sql Server. In any case you should add the parameters in the OleDbCommand collection in the same order in which the named placeholders appears in your query. So you need this order:
cmd.Parameters.Add("#Age_Group", OleDbType.VarChar).Value = Me.cb_AgeGroup.Text
cmd.Parameters.Add("#Surname", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txt_Surname.Text)) > 0, Me.txt_Surname.Text, DBNull.Value)
cmd.Parameters.Add("#Forename", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txt_Forename.Text)) > 0, Me.txt_Forename.Text, DBNull.Value)
cmd.Parameters.Add("#Rating", OleDbType.VarChar).Value = Me.cb_Rating.Text
cmd.Parameters.Add("#DOB", OleDbType.Date).Value = Me.dtp_DOB.Text
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = Me.txt_Address.Text
cmd.Parameters.Add("#Email", OleDbType.VarChar).Value = Me.txt_Email.Text
cmd.Parameters.Add("#Position", OleDbType.VarChar).Value = Me.cb_Position.Text
cmd.Parameters.Add("#Foot", OleDbType.VarChar).Value = Me.cb_Foot.Text
cmd.Parameters.Add("#Mins_Played", OleDbType.VarChar).Value = Me.nup_MinsPlayed.Text
cmd.Parameters.Add("#Goals", OleDbType.VarChar).Value = Me.nup_Goals.Text
cmd.Parameters.Add("#Assists", OleDbType.VarChar).Value = Me.nup_Assists.Text
cmd.Parameters.Add("#Yellow_Cards", OleDbType.VarChar).Value = Me.nup_YellowCards.Text
cmd.Parameters.Add("#Red_Cards", OleDbType.VarChar).Value = Me.nup_RedCards.Text
and this last parameter should be added only if you have the UPDATE path not for the INSERT. (Assuming the ID column to be an AutoIncrement one)
If Me.txt_Forename.Tag <> 0 Then
cmd.Parameters.Add("#ID", OleDbType.Numeric).Value = Me.txt_Forename.Tag
End If
Also another problem at the end when you try to read the ##IDENTITY value. Using the same command is fine, but you need to clear the parameters collection
If Me.txt_Forename.Tag = 0 Then
cmd.Parameters.Clear()
cmd.CommandText = "Select ##Identity"
Me.txt_Forename.Tag = cmd.ExecuteScalar()
End If

Related

How to refresh database between Inserting and Selecting

I am trying to get data from a record in a database that has just been creating, but no data is found from it.
I've tried using different connections in the hope that it would be able to 'see' the new data, but this doesn't work and I am stuck!
Using oCmd As New OleDbCommand("Insert Into Users (FirstName, LastName, Username, `Password`, Teacher) Values (#firstName, #lastName, #username, #password, 0)", myConnection)
oCmd.Parameters.Add("#firstName", OleDbType.VarChar, 255).Value = txtFirstName.Text
oCmd.Parameters.Add("#lastNamee", OleDbType.VarChar, 255).Value = txtLastName.Text
oCmd.Parameters.Add("#username", OleDbType.VarChar, 255).Value = txtUsername.Text
oCmd.Parameters.Add("#password", OleDbType.VarChar, 255).Value = txtPassword.Text
oCmd.ExecuteNonQuery()
End Using
Dim userID As String = ""
Using ocmd As New OleDbCommand("Select * From Users Where FirstName = #firstName And LastName = #lastName", myConnection)
ocmd.Parameters.Add("#firstName", OleDbType.Char, 255).Value = txtFirstName.Text
ocmd.Parameters.Add("#lastName", OleDbType.Char, 255).Value = txtLastName.Text
Dim dataReader As OleDbDataReader = ocmd.ExecuteReader()
While dataReader.Read
userID = dr("UserID")
End While
The error that is shown is
System.InvalidOperationException: 'No data exists for the row/column.'
All I want is to get the userID of the record that has been created. Any help is appreciated.
To get the last entered ID.
Dim cmd1 As New OleDbCommand("Select ##IDENTITY", myConnection)
Dim itgID As Integer = CInt(cmd1.ExecuteScalar)

Avoiding Cross Side Scripting in asp.net

I am currently coding a registration module. Basically, it's a registration module that takes the user info from asp.net site and sends them to the SQL server. I made significant changes but I still have XSS issues when I scan it with acunetix. The registration module works just fine but I wanted to avoid XSS. Because it's clearly vulnerable and it did not pass the acunetix scan.
The last code that I came up with is below. It's a button click event.
Dim connQuery As String = "Data Source=myserver;Initial Catalog=mydatabase;Integrated Security=True"
Dim cs As SqlConnection = New SqlConnection(connQuery)
Dim da As SqlDataAdapter = New SqlDataAdapter()
Dim table As String = "[mydatabase].[dbo].[users]"
Dim query As String = "INSERT INTO " & table & "(passwd, FName, LName, Organization, TelNo, FaxNo, Title, Email, User_type, GroupID, Activated, request_num, FirstLogin, LastLogin, IsLoggedin, IsOutsideInv, WI, study_type) VALUES (#passwd, #FName, #LName, #Organization, #TelNo, #FaxNo, #Title, #Email, #User_type, #GroupID, #Activated, #request_num, #FirstLogin, #LastLogin, #IsLoggedin, #IsOutsideInv, #WI, #study_type)"
Try
da.InsertCommand = New SqlCommand(query, cs)
' da.InsertCommand.Parameters.Add("#passwd", SqlDbType.NVarChar).Value = txtPassword.Text
da.InsertCommand.Parameters.Add("#passwd", SqlDbType.NVarChar).Value = encode(txtPassword.Text)
da.InsertCommand.Parameters.Add("#FName", SqlDbType.NVarChar).Value = txtFirstName.Text
da.InsertCommand.Parameters.Add("#LName", SqlDbType.NVarChar).Value = txtLastName.Text
da.InsertCommand.Parameters.Add("#Organization", SqlDbType.NVarChar).Value = txtOrg.Text
da.InsertCommand.Parameters.Add("#TelNo", SqlDbType.NVarChar).Value = txtPhone.Text
da.InsertCommand.Parameters.Add("#FaxNo", SqlDbType.NVarChar).Value = txtFax.Text
da.InsertCommand.Parameters.Add("#Title", SqlDbType.NVarChar).Value = txtTitle.Text
da.InsertCommand.Parameters.Add("#Email", SqlDbType.NVarChar).Value = txtEmail.Text
da.InsertCommand.Parameters.Add("#User_type", SqlDbType.Int).Value = 0
da.InsertCommand.Parameters.Add("#GroupID", SqlDbType.NVarChar).Value = 0
da.InsertCommand.Parameters.Add("#Activated", SqlDbType.Bit).Value = 0
da.InsertCommand.Parameters.Add("#request_num", SqlDbType.Int).Value = 0
da.InsertCommand.Parameters.Add("#FirstLogin", SqlDbType.DateTime).Value = DateAndTime.Now
da.InsertCommand.Parameters.Add("#LastLogin", SqlDbType.NVarChar).Value = DateAndTime.Now
da.InsertCommand.Parameters.Add("#IsLoggedin", SqlDbType.Bit).Value = 0
da.InsertCommand.Parameters.Add("#IsOutsideInv", SqlDbType.NVarChar).Value = 0
da.InsertCommand.Parameters.Add("#WI", SqlDbType.NVarChar).Value = txtInves.Text
da.InsertCommand.Parameters.Add("#study_type", SqlDbType.NVarChar).Value = 0
cs.Open()
da.InsertCommand.ExecuteNonQuery()
cs.Close()
Catch ex As Exception
Labelmessage.Text = "Error while adding record to the database ==> " & ex.Message.ToString()
Finally
cs.Close()
End Try
What would be the ideal way to pass this scan? I would appreciate any help.

How to stop loop

I have a problem with Do until loop. When the record successfully saved and message-box appeared, after clicking the OK button it just shows the message-box and repeat it endlessly. I don't know what's the code for that. Please help.
MySqlConn.Open()
Dim last, midd, first, age, occu, phone As MySqlDataReader
Dim cmd1, cmd2, cmd3, cmd4, cmd5, cmd6, cmd7, cmd8, cmd9, cmd10, cmd11 As New MySqlCommand
Dim query1, query2, query3, query4, query5, query6, query7, query8, query9, query10, query11 As String
'lastname query
query1 = "SELECT * FROM newpatient WHERE Lastname ='" & txtLastname.Text & "'"
cmd1 = New MySqlCommand(query1, MySqlConn)
last = cmd1.ExecuteReader
'first query
query2 = "SELECT * FROM newpatient WHERE Firstname ='" & txtFirstname.Text & "'"
cmd2 = New MySqlCommand(query2, MySqlConn)
last.Close()
first = cmd2.ExecuteReader
'middle query
query3 = "SELECT * FROM newpatient WHERE Middlename ='" & txtMiddlename.Text & "'"
cmd3 = New MySqlCommand(query3, MySqlConn)
first.Close()
midd = cmd3.ExecuteReader
'age query
query4 = "SELECT * FROM newpatient WHERE Age ='" & txtAge.Text & "'"
cmd4 = New MySqlCommand(query4, MySqlConn)
midd.Close()
age = cmd4.ExecuteReader
'gender query
query5 = "SELECT * FROM newpatient WHERE Occupation ='" & txtOccupation.Text & "'"
cmd5 = New MySqlCommand(query5, MySqlConn)
age.Close()
occu = cmd5.ExecuteReader
'phone query
query6 = "SELECT * FROM newpatient WHERE Mobile_Number ='" & txtMobileNumber.Text & "'"
cmd6 = New MySqlCommand(query6, MySqlConn)
occu.Close()
phone = cmd6.ExecuteReader
Do While last.HasRows = 0 And first.HasRows = 0 And midd.HasRows = 0 And occu.HasRows = 0 And phone.HasRows = 0 And age.HasRows = 0
Dim cmd As MySqlCommand = MySqlConn.CreateCommand
cmd.CommandText = String.Format("INSERT INTO newpatient (ID, Lastname, Firstname, Middlename, Age, Mobile_Number, Gender, Address, Occupation, Month, Day, Year )" &
"VALUES ('{0}' ,'{1}' ,'{2}' ,'{3}' ,'{4}' ,'{5}' , '{6}', '{7}', '{8}', '{9}', '{10}', '{11}' )",
txtID.Text,
txtLastname.Text,
txtFirstname.Text,
txtMiddlename.Text,
txtAge.Text,
txtMobileNumber.Text,
cmbGender.SelectedItem,
txtAddress.Text,
txtOccupation.Text,
cmbMonth.SelectedItem,
cmbDay.SelectedItem,
cmbYear.SelectedItem)
phone.Close()
Dim affectedrows As Integer = cmd.ExecuteNonQuery()
If affectedrows > 0 Then
MsgBox("Record successfully saved!", MsgBoxStyle.Information, "Success")
'AUTO GENERATE RANDOM IDs
Dim random As New Random
Dim id As Integer
id = (random.Next(100000000, 1000000000))
txtID.Text = id
'CLEARS TEXTBOXES
txtMobileNumber.Text = ""
txtLastname.Text = ""
txtFirstname.Text = ""
txtMiddlename.Text = ""
txtAge.Text = 0
cmbGender.SelectedItem = ""
cmbDay.SelectedItem = ""
cmbMonth.SelectedItem = ""
cmbYear.SelectedItem = 0
txtAddress.Text = ""
txtOccupation.Text = ""
txtLastname.Select()
Else
MsgBox("Saving record failed.", MsgBoxStyle.Critical, "Failed")
'AUTO GENERATE RANDOM IDs
Dim random As New Random
Dim id As Integer
id = (random.Next(100000000, 1000000000))
txtID.Text = id
'CLEARS TEXTBOXES
txtMobileNumber.Text = ""
txtLastname.Text = ""
txtFirstname.Text = ""
txtMiddlename.Text = ""
txtAge.Text = 0
cmbGender.SelectedItem = ""
cmbDay.SelectedItem = ""
cmbMonth.SelectedItem = ""
cmbYear.SelectedItem = 0
txtAddress.Text = ""
txtOccupation.Text = ""
txtLastname.Select()
End If
Loop
'CLEARS TEXTBOXES
txtMobileNumber.Text = ""
txtLastname.Text = ""
txtFirstname.Text = ""
txtMiddlename.Text = ""
txtAge.Text = 0
cmbGender.SelectedItem = ""
cmbDay.SelectedItem = ""
cmbMonth.SelectedItem = ""
cmbYear.SelectedItem = 0
txtAddress.Text = ""
txtOccupation.Text = ""
MsgBox("Patient has already registered!", MsgBoxStyle.Critical, "Already registered")
MySqlConn.close()
To stop the loop requires a call to Exit, like so:
Exit Do
Having said that, you should never just call Exit without requiring a condition to be met, or you can encounter unexpected behavior.
But you've got much larger problems here. I'm going to list them out quickly and include a quick pseudocode suggestion (as in I've never used MySql in .Net, so not at all familiar with the API, so this code WILL need modified before it would work)
Dim cmd As MySqlCommand = MySqlConn.CreateCommand
cmd.CommandText = "INSERT INTO newpatient (ID, Lastname, Firstname, Middlename, Age, Mobile_Number, Gender, Address, Occupation, Month, Day, Year )" &
"VALUES (:ID, :Lastname, :Firstname, :Middlename, :Age, :Mobile_Number, :Gender, :Address, :Occupation, :Month, :Day, :Year)"
cmd.Parameters.Add(new MySqlParameter(":ID", txtID.Text))
cmd.Parameters.Add(new MySqlParameter(":Lastname", txtLastname.Text))
cmd.Parameters.Add(new MySqlParameter(":Firstname", txtFirstname.Text))
cmd.Parameters.Add(new MySqlParameter(":Middlename", txtMiddlename.Text))
cmd.Parameters.Add(new MySqlParameter(":Age", txtAge.Text))
cmd.Parameters.Add(new MySqlParameter(":Mobile_Number", txtMobileNumber.Text))
cmd.Parameters.Add(new MySqlParameter(":Gender", cmbGender.SelectedItem))
cmd.Parameters.Add(new MySqlParameter(":Address", txtAddress.Text))
cmd.Parameters.Add(new MySqlParameter(":Occupation", txtOccupation.Text))
cmd.Parameters.Add(new MySqlParameter(":Month", cmbMonth.SelectedItem))
cmd.Parameters.Add(new MySqlParameter(":Day", cmbDay.SelectedItem))
cmd.Parameters.Add(new MySqlParameter(":Year", cmbYear.SelectedItem))
Dim affectedrows As Integer = cmd.ExecuteNonQuery()
If affectedrows = 1 Then
MsgBox("Record successfully saved!", MsgBoxStyle.Information, "Success")
Else
If affectedrows = 0 Then
'Most likely the record already existed, call an update here and if you get 1 result, the record existed and you just saved changes
MsgBox("Patient has already registered!", MsgBoxStyle.Critical, "Already registered")
'You could change the above to a Yes/No question about updating the record and have the result in an if to update the record at the user's discretion.
cmd = MySqlConn.CreateCommand
cmd.CommandText = "UPDATE newpatient " &
"SET Lastname = :Lastname, Firstname = :Firstname, Middlename = :Middlename, Age = :Age, Mobile_Number = :Mobile_Number, " &
" Gender = :Gender, Address = :Address, Occupation = :Occupation, Month = :Month, Day = :Day, Year = :Year " &
"WHERE ID = :ID"
cmd.Parameters.Add(new MySqlParameter(":ID", txtID.Text))
cmd.Parameters.Add(new MySqlParameter(":Lastname", txtLastname.Text))
cmd.Parameters.Add(new MySqlParameter(":Firstname", txtFirstname.Text))
cmd.Parameters.Add(new MySqlParameter(":Middlename", txtMiddlename.Text))
cmd.Parameters.Add(new MySqlParameter(":Age", txtAge.Text))
cmd.Parameters.Add(new MySqlParameter(":Mobile_Number", txtMobileNumber.Text))
cmd.Parameters.Add(new MySqlParameter(":Gender", cmbGender.SelectedItem))
cmd.Parameters.Add(new MySqlParameter(":Address", txtAddress.Text))
cmd.Parameters.Add(new MySqlParameter(":Occupation", txtOccupation.Text))
cmd.Parameters.Add(new MySqlParameter(":Month", cmbMonth.SelectedItem))
cmd.Parameters.Add(new MySqlParameter(":Day", cmbDay.SelectedItem))
cmd.Parameters.Add(new MySqlParameter(":Year", cmbYear.SelectedItem))
affectedrows = cmd.ExecuteNonQuery()
If affectedrows = 1 Then
MsgBox("Record successfully saved!", MsgBoxStyle.Information, "Success")
Else
MsgBox("Saving record failed.", MsgBoxStyle.Critical, "Failed")
End If
Else
'Should never get here. We covered 0 and 1 in the other two logic branches.
'In this small demo, handling when more than 1 record gets updated is out of scope.
End If
End If
'CLEARS TEXTBOXES
txtMobileNumber.Text = ""
txtLastname.Text = ""
txtFirstname.Text = ""
txtMiddlename.Text = ""
txtAge.Text = 0
cmbGender.SelectedItem = ""
cmbDay.SelectedItem = ""
cmbMonth.SelectedItem = ""
cmbYear.SelectedItem = 0
txtAddress.Text = ""
txtOccupation.Text = ""
txtLastname.Select()
MySqlConn.close()
Never build queries from strings where you rely on a user for some of those strings. This leaves you vulnerable to SQL injection attacks (try putting a name with an apostrophe in it in one of the name fields and watch the flurry of errors. Then realize someone with malicious intentions could do serious damage to your database if you don't sanitize your inputs) Always parameterize your queries wherever possible!!
Don't repeat yourself! (AKA the DRY principle) If you find yourself copying/pasting the same block of code from place to place, that means you're doing something wrong. In this case, it was that you got stuck on the idea that you HAD to have a loop, and to make sure you're input fields were cleared, you just copied the code to clear them to 3 different places in the codepath. If you find that you NEED to run the same code repeatedly throughout your programs codepath, then generalize it and put it in a function. Your eyes and the eyes of the next person to read/maintain your code will appreciate it!
You need some more knowledge/experience with SQL, and that's ok, everyone had to start somewhere. In the sample, I removed ALL of your select queries in favor of trying ONE insert query and branching the logic based on the result of that 1 query. Much easier to read/maintain. Also, Identity values should be handle BY your sql instance, not in code. You generally want them used sequentially to avoid collisions and you don't want them modified by/visible to end users. Correcting the properties of the ID column allows removal of the random generation code. Just remember that when you insert into a table with an identity column that you don't need to include the identity column in your INSERT statement (SQL will fill that column for you)

Operator not defined error?

I am trying to update a record but I get the error: Operator '=' is not defined for type 'Date' and type 'Integer'. How can I fix this?
If Me.txt_Team.Tag = 0 Then
sSQL = "INSERT INTO FixtureandResultsDatabase (Fixture_Date, Team, Ground, Score)"
sSQL = sSQL & " VALUES(?, ?, ?, ?)"
cmd.CommandText = sSQL
Else
sSQL = "UPDATE FixtureandResultsDatabase set Fixture_Date = #Fixture_Date, Team = #Team, Ground = #Ground, Score = #Score WHERE ID = #id"
cmd.CommandText = sSQL
End If
cmd.Parameters.Add("#Fixture_Date", OleDbType.Date).Value = Me.dtp_Date.Text
cmd.Parameters.Add("#Team", OleDbType.VarChar).Value = Me.txt_Team.Text
cmd.Parameters.Add("#Ground", OleDbType.VarChar).Value = Me.cb_Ground.Text
cmd.Parameters.Add("#Score", OleDbType.VarChar).Value = Me.txt_Score.Text
If Me.txt_Team.Tag <> 0 Then
cmd.Parameters.Add("#ID", OleDbType.Numeric).Value = Me.txt_Team.Tag
End If
cmd.ExecuteNonQuery()
If Me.txt_Team.Tag = 0 Then
cmd.Parameters.Clear()
cmd.CommandText = "Select ##Identity"
Me.txt_Team.Tag = cmd.ExecuteScalar()
End If
MsgBox("Database has been updated.")
conn.Close()
Fix it like this
Instead of
cmd.Parameters.Add("#Fixture_Date", OleDbType.Date).Value = Me.dtp_Date.Text
Do
cmd.Parameters.Add("#Fixture_Date", OleDbType.Date).Value = Me.dtp_Date.Value
You should post your table structure [sp_help 'tableName']. You obviously have date field but you trying to set value [object] to string - Me.dtp_Date.Text.
On another note - get rid OleDB ASAP - use SqlClient. oleDb will be decommissioned soon. Also, you can use Output Inserted.Id in your update and insert with ExecuteScalar instead of ExecuteNonQuery. It will return your identity all in one statement - instead of Select ##Identity.

Insert multiple rows in access database using oledb parameters

I am trying to insert multiple rows in a listitems to a database using parameters.
But it won't give me any errors, and also won't insert any data in the table.
does anyone have any ideas on this one?
strSQL = "insert into tbltrans2 (transid,itemcode,itemname,qty,price,[total],btw) values ( ?,?,?,?,?,?,?)"
Using cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\POS.mdb"), _
cmd As New OleDbCommand(strSQL, cn)
cmd.Parameters.Add("?", OleDbType.VarChar).Value = txtTransId.Text
cmd.Parameters.Add("?", OleDbType.VarChar, 10)
cmd.Parameters.Add("?", OleDbType.VarChar, 50)
cmd.Parameters.Add("?", OleDbType.Integer)
cmd.Parameters.Add("?", OleDbType.Decimal)
cmd.Parameters.Add("?", OleDbType.Decimal)
cmd.Parameters.Add("?", OleDbType.VarChar, 50)
cn.Open()
For Each ls As ListViewItem In ListItems.Items
cmd.Parameters(1).Value = ls.Tag
cmd.Parameters(2).Value = ls.SubItems(0).Text
cmd.Parameters(3).Value = Integer.Parse(ls.SubItems(1).Text)
cmd.Parameters(4).Value = Decimal.Parse(ls.SubItems(2).Text)
cmd.Parameters(5).Value = Decimal.Parse(ls.SubItems(3).Text)
cmd.Parameters(6).Value = ls.SubItems(5).Text
Next ls
End Using
Hey steve, When I try that, it gives me 'syntax error in update statement' erro. Here is my code:
Try
strSQL = "UPDATE set instock = ? where itemcode= ?"
Using cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\POS.mdb"), _
cmd As New OleDbCommand(strSQL, cn)
cn.Open()
For Each ls As ListViewItem In ListItems.Items
cmd.Parameters.Add("?", OleDbType.Integer).Value = 100
cmd.Parameters.Add("?", OleDbType.VarChar).Value = ls.Tag
cmd.ExecuteNonQuery()
Next ls
cn.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
Now, I still need help with decreasing the stock. Here is the code that I use, but it isn't working.
strSQL = "UPDATE tblitem set instock ='instock'- ? where itemcode = ?"
Using cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\POS.mdb"), _
cmd As New OleDbCommand(strSQL, cn)
cn.Open()
For Each ls As ListViewItem In SalesListItems.Items
If Not (ls.SubItems(1).Tag(0) = "n") Then
cmd.Parameters.Add("?", OleDbType.Integer).Value = ls.SubItems(1).Text
cmd.Parameters.Add("?", OleDbType.VarChar, 10).Value = ls.Tag
cmd.ExecuteNonQuery()
End If
Next ls
cn.Close()
End Using
You are missing the execute part
For Each ls As ListViewItem In ListItems.Items
cmd.Parameters(1).Value = ls.Tag
cmd.Parameters(2).Value = ls.SubItems(0).Text
cmd.Parameters(3).Value = Integer.Parse(ls.SubItems(1).Text)
cmd.Parameters(4).Value = Decimal.Parse(ls.SubItems(2).Text)
cmd.Parameters(5).Value = Decimal.Parse(ls.SubItems(3).Text)
cmd.Parameters(6).Value = ls.SubItems(5).Text
cmd.ExecuteNonQuery()
Next ls
Also, are you certain on the input values coming from the subitems? If there isn't a control on their effective numeric value when you add them to the ListView, then the loop could fail with an exception when you try to convert the supposed numeric value with Parse.
EDIT: This instead for an update
strSQL = "UPDATE tblitem set instock = ? where itemcode= ?"
Using cn As New OleDbConnection("......")
cmd As New OleDbCommand(strSQL, cn)
cmd.Parameters.Add("?", OleDbType.Integer).Value = 100
cmd.Parameters.Add("?", OleDbType.VarChar).Value = yourItemCodeValue
cmd.ExecuteNonQuery()
End Using
Keep in mind that I suppose instock is a integer data type and itemcode a varchar.