How to refresh database between Inserting and Selecting - sql

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)

Related

VB Get Autonum values

I use the first "Using" statement below to insert a row to a table called "Archives". This table has a primary key that is an autonum in an Access db. The second Using statement I use to retrieve the value for the autonum field, searching by the parameters that I just entered. While this works perfectly well, it just seems ugly. Is there a way to get the autonum field returned to me after the insert? (BTW - I have deleted some code from between these two statements so if it looks a little strange, that may be why.
Using myConn As New OleDbConnection(strConnectionString),
myInsertCommand As New OleDbCommand("INSERT INTO Archives (ArchUserName, ArchUserDomain, ArchDate, ArchRoot, ArchStatus)
VALUES (#strArchUser, #strArchUserDomain, #dteArchDate, #strArchRoot, #strArchStatus);", myConn)
myInsertCommand.Parameters.Add("#strArchUser", OleDbType.VarChar, 100).Value = strArchUser
myInsertCommand.Parameters.Add("#strArchDomain", OleDbType.VarChar, 100).Value = strArchDomain
myInsertCommand.Parameters.Add("#dteArchDate", OleDbType.Date, 20).Value = dteArchDate
myInsertCommand.Parameters.Add("#strArchRoot", OleDbType.VarChar, 255).Value = strArchRoot
myInsertCommand.Parameters.Add("#strArchStatus", OleDbType.VarChar, 100).Value = strArchStatus
myConn.Open()
myInsertCommand.ExecuteNonQuery()
End Using
Dim sql As String = "SELECT ArchID
FROM Archives
WHERE ArchUserName = #ArchUserName
AND ArchUserDomain = #ArchUserDomain
AND ArchDate = #ArchDate
AND ArchRoot = #ArchRoot"
Using myConn As New OleDbConnection(strConnectionString),
command As New OleDbCommand(sql, myConn)
With command.Parameters
.Add("#ArchUserName", OleDbType.VarChar, 50).Value = strArchUser
.Add("#ArchUserDomain", OleDbType.VarChar, 50).Value = strArchDomain
.Add("#ArchDate", OleDbType.Date).Value = dteArchDate
.Add("#ArchRoot", OleDbType.VarChar, 50).Value = strArchRoot
End With
myConn.Open()
strArchID = "Arch" & CStr(command.ExecuteScalar())
strDirectoryName = "Archive" & CStr(command.ExecuteScalar())
ReturnCode = 0
End Using
Use ##Identity on the same connection immediately after the insert.
Private Function InsertArchiveRetrieveID(strArchUser As String, strArchDomain As String, dteArchDate As Date, strArchRoot As String, strArchStatus As String) As Integer
Dim NewID As Integer
Using myConn As New OleDbConnection(strConnectionString),
myInsertCommand As New OleDbCommand("INSERT INTO Archives (ArchUserName, ArchUserDomain, ArchDate, ArchRoot, ArchStatus)
VALUES (#strArchUser, #strArchUserDomain, #dteArchDate, #strArchRoot, #strArchStatus);", myConn)
With myInsertCommand.Parameters
.Add("#strArchUser", OleDbType.VarChar, 100).Value = strArchUser
.Add("#strArchDomain", OleDbType.VarChar, 100).Value = strArchDomain
.Add("#dteArchDate", OleDbType.Date, 20).Value = dteArchDate
.Add("#strArchRoot", OleDbType.VarChar, 255).Value = strArchRoot
.Add("#strArchStatus", OleDbType.VarChar, 100).Value = strArchStatus
End With
myConn.Open()
myInsertCommand.ExecuteNonQuery()
Using RetrieveNewIDCommand As New OleDbCommand("Select ##Identity From Archives,", myConn)
NewID = CInt(RetrieveNewIDCommand.ExecuteScalar)
End Using
End Using
Return NewID
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim NewID = InsertArchiveRetrieveID(txtUser.Text, txtDomain.Text, DateTimePicker1.Value, txtRoot.Text, txtStatus.Text)
Dim strArchID = "Arch" & CStr(NewID)
Dim strDirectoryName = "Archive" & CStr(NewID)
End Sub

How to use VB and SQL to add Records to a Relational Database in Access

I'm working in Visual Basic to create a forms applications as part of a college project. I've used SQL statements to read from the access database but I'm having some trouble writing to it. I'd like to hazard a guess it's due to the database having relationships between tables.
This is my first go at making something substantial, and vb is not my language of choice. Expect the code to be poor at best. If anyone has links to resources that I could use to improve I'd be immensely grateful.
Exception:
Exception thrown: 'System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.'
Exception location: 'commAddToStaff.ExecuteNonQuery()'
Both try statements are catching exceptions when ran. I've attempted providing data in the parameters rather than using data from a text box, but this hasn't resolved the issue.
Code:
Private Sub btnAddStaffMember_Click(sender As Object, e As EventArgs) Handles btnAddStaffMember.Click
'Dimension tblStaff Parameters
Dim AddEmployeeIDParam As New OleDb.OleDbParameter("#AddEmployeeID", txtAddEmployeeID.Text)
Dim AddForenameParam As New OleDb.OleDbParameter("#AddForename", txtAddForename.Text)
Dim AddSurnameParam As New OleDb.OleDbParameter("#AddSurname", txtAddSurname.Text)
Dim AddDOBParam As New OleDb.OleDbParameter("#AddDOB", txtAddDOB.Text)
Dim AddUserTierParam As New OleDb.OleDbParameter("#AddUserTier", txtAddUserTier.Text)
'Dimension tblContacts Parameters
Dim conContact As New OleDb.OleDbConnection("Provider=Microsoft.......")
Dim commContactCount As New OleDb.OleDbCommand("Select Count(*) FROM tblContacts", conContact)
commContactCount.Connection.Open()
Dim ContactID = commContactCount.ExecuteScalar + 1 'Calculate the contactID of the new record
commContactCount.Connection.Close() 'Close the connection
Dim AddContactIDParam As New OleDb.OleDbParameter("#AddContactID", ContactID)
Dim AddAddressParam As New OleDb.OleDbParameter("#AddAddress", txtAddAddress.Text)
Dim AddPostcodeParam As New OleDb.OleDbParameter("#AddPostcode", txtAddPostcode.Text)
Dim AddEmailParam As New OleDb.OleDbParameter("#AddEmail", txtAddEmail.Text)
Dim AddMobileNoParam As New OleDb.OleDbParameter("#AddMobileNo", txtAddMobileNumber.Text)
Dim conAddToStaff As New OleDb.OleDbConnection("Provider=Microsoft....")
Dim commAddToStaff As New OleDb.OleDbCommand("Insert Into tblStaff (EmployeeID, Forename, Surname, DOB, User_Tier, ContactID) Values (#AddEmployeeID, #AddForename, #AddSurname, #AddDOB, #AddUserTier, #AddContactID)", conAddToStaff)
commAddToStaff.Parameters.Add(AddEmployeeIDParam)
commAddToStaff.Parameters.Add(AddForenameParam)
commAddToStaff.Parameters.Add(AddSurnameParam)
commAddToStaff.Parameters.Add(AddDOBParam)
commAddToStaff.Parameters.Add(AddUserTierParam)
Dim commAddToContact As New OleDb.OleDbCommand("Insert Into tblContacts (ContactID, Address, Postcode, Email, Mobile_Number) Values (#AddContactID, #AddAddress, #AddPostcode, #AddEmail, #AddMobileNo)", conContact)
commAddToContact.Parameters.Add(AddContactIDParam)
commAddToContact.Parameters.Add(AddAddressParam)
commAddToContact.Parameters.Add(AddPostcodeParam)
commAddToContact.Parameters.Add(AddEmailParam)
commAddToContact.Parameters.Add(AddMobileNoParam)
Try
commAddToStaff.Connection.Open() 'Open a connection to the database
commAddToStaff.ExecuteNonQuery() 'Execute the command
commAddToStaff.Connection.Dispose() 'Remove unmanaged resources
commAddToStaff.Connection.Close() 'Close the connection
Catch ex As Exception
MessageBox.Show("Error with staff")
End Try
Try
commAddToContact.Connection.Open() 'Open a connection to the database
commAddToContact.ExecuteNonQuery() 'Execute the command
commAddToContact.Connection.Dispose() 'Remove unmanaged resources
commAddToContact.Connection.Close() 'Close the connection
Catch ex As Exception
MessageBox.Show("Error with contacts")
End Try
MessageBox.Show("Reached")
Me.Hide() 'Close the Current screen
StaffDB_Add_Staff_Security_Question.Show() 'Open the Add Security Question Screen
End Sub
You are inserting six values into six columns here:
Dim commAddToStaff As New OleDb.OleDbCommand("Insert Into tblStaff (EmployeeID, Forename, Surname, DOB, User_Tier, ContactID) Values (#AddEmployeeID, #AddForename, #AddSurname, #AddDOB, #AddUserTier, #AddContactID)", conAddToStaff)
but you only add five parameters to the command here:
commAddToStaff.Parameters.Add(AddEmployeeIDParam)
commAddToStaff.Parameters.Add(AddForenameParam)
commAddToStaff.Parameters.Add(AddSurnameParam)
commAddToStaff.Parameters.Add(AddDOBParam)
commAddToStaff.Parameters.Add(AddUserTierParam)
Where's the parameter for the #AddContactID placeholder in the SQL code?
EDIT:
For the record, here's how I would tend to write code for that sort of task, ignoring the horrible way you're generating the ContactID value:
Using connection As New OleDbConnection("connection string here")
connection.Open()
Dim contactCount As Integer
Using contactCountCommand As New OleDbCommand("SELECT COUNT(*) FROM tblContacts", connection)
contactCount = CInt(contactCountCommand.ExecuteScalar())
End Using
Dim contactId = contactCount + 1
Using staffCommand As New OleDbCommand("INSERT INTO tblStaff (EmployeeID, Forename, Surname, DOB, User_Tier, ContactID) Values (#EmployeeID, #Forename, #Surname, #DOB, #User_Tier, #ContactID)", connection)
With staffCommand.Parameters
.Add("#EmployeeID", OleDbType.VarChar, 50).Value = txtAddEmployeeID.Text
.Add("#Forename", OleDbType.VarChar, 50).Value = txtAddForename.Text
.Add("#Surname", OleDbType.VarChar, 50).Value = txtAddSurname.Text
.Add("#DOB", OleDbType.Date).Value = CDate(txtAddDOB.Text) 'Why isn't this coming from a DateTimePicker?
.Add("#User_Tier", OleDbType.VarChar, 50).Value = txtAddUserTier.Text
.Add("#ContactID", OleDbType.Integer).Value = contactId
End With
staffCommand.ExecuteNonQuery()
End Using
Using contactCommand As New OleDbCommand("INSERT INTO tblContacts (ContactID, Address, Postcode, Email, Mobile_Number) Values (#ContactID, #Address, #Postcode, #Email, #Mobile_Number)", connection)
With contactCommand.Parameters
.Add("#ContactID", OleDbType.Integer).Value = contactId
.Add("#Address", OleDbType.VarChar, 50).Value = txtAddAddress.Text
.Add("#Postcode", OleDbType.VarChar, 50).Value = txtAddPostcode.Text
.Add("#Email", OleDbType.VarChar, 50).Value = txtAddEmail.Text
.Add("#Mobile_Number", OleDbType.VarChar, 50).Value = txtAddMobileNumber.Text
End With
contactCommand.ExecuteNonQuery()
End Using
End Using
It would be easier to see where there are insufficient parameters added by rearranging the code into smaller pieces, where related items are near to each other. Something like:
Imports System.Data.OleDb
Public Class Form1
Dim connStr As String = "Provider=Microsoft......."
Sub AddStaffMemberToDatabase(contactId As Integer)
Dim sql = "INSERT INTO tblStaff (EmployeeID, Forename, Surname, DOB, UserTier, ContactID) VALUES (#AddEmployeeID, #AddForename, #AddSurname, #AddDOB, #AddUserTier, #AddContactID)"
Using conn As New OleDbConnection(connStr),
cmd As New OleDbCommand(sql, conn)
Dim dob = DateTime.Parse(txtAddDOB.Text)
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddEmployeeID", .OleDbType = OleDbType.VarChar, .Size = 20, .Value = txtAddEmployeeID.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddForename", .OleDbType = OleDbType.VarWChar, .Size = 255, .Value = txtAddForename.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddSurname", .OleDbType = OleDbType.VarWChar, .Size = 255, .Value = txtAddSurname.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddDOB", .OleDbType = OleDbType.Date, .Value = dob})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddUserTier", .OleDbType = OleDbType.VarChar, .Size = 20, .Value = txtAddUserTier.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddContactID", .OleDbType = OleDbType.Integer, .Value = contactId})
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
Sub AddContactToDatabase(contactId As Integer)
Dim sql = "INSERT INTO tblContacts (ContactID, Address, Postcode, Email, Mobile_Number) VALUES (#AddContactID, #AddAddress, #AddPostcode, #AddEmail, #AddMobileNo)"
Using conn As New OleDbConnection(connStr),
cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddContactID", .OleDbType = OleDbType.Integer, .Value = contactId})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddAddress", .OleDbType = OleDbType.VarWChar, .Size = 255, .Value = txtAddAddress.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#txtAddPostcode", .OleDbType = OleDbType.VarChar, .Size = 20, .Value = txtAddPostcode.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddEmail", .OleDbType = OleDbType.VarWChar, .Size = 255, .Value = txtAddEmail.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddMobileNo", .OleDbType = OleDbType.VarChar, .Size = 20, .Value = txtAddMobileNumber.Text})
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
Sub AddStaffMember()
Dim sql = "SELECT COUNT(*) FROM tblContacts"
Dim contactID As Integer
Using conn As New OleDbConnection(connStr),
cmd As New OleDbCommand(sql, conn)
conn.Open()
contactID = Convert.ToInt32(cmd.ExecuteScalar()) + 1
End Using
AddStaffMemberToDatabase(contactID)
AddContactToDatabase(contactID)
End Sub
Private Sub btnAddStaffMember_Click(sender As Object, e As EventArgs) Handles btnAddStaffMember.Click
AddStaffMember()
Me.Hide()
StaffDB_Add_Staff_Security_Question.Show() 'Open the Add Security Question Screen
End Sub
End Class
The Using statement makes sure that "unamanaged resources" are released when the code has finished with them.
Note that you will need to provide a more specific and robust way of parsing the DOB text (e.g. DateTime.TryParseExact). Also, the database types and sizes need to be edited to match the declarations in the database.

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.

VB.Net SQL Insert Statement seems to work but doesn't actually change Database

This is the code:
Dim insertSql As String = "INSERT INTO StudentTable(BadgeNo,FirstName,LastName,SAPID,Email,Phone,College) VALUES (?,?,?,?,?,?,?)"
Dim connStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""C:\Users\larsennicholasg\Documents\Visual Studio 2012\Projects\SSCLogin\SSCLogin\My Project\SSCStudent.mdb"""
Using conn As New OleDbConnection(connStr), cmd As New OleDbCommand(insertSql, conn)
cmd.Parameters.Add("?", OleDbType.Integer).Value = CInt(BadgeNoTextBox.Text)
cmd.Parameters.Add("?", OleDbType.WChar, 255).Value = FirstNameTextBox.Text
cmd.Parameters.Add("?", OleDbType.WChar, 255).Value = LastNameTextBox.Text
cmd.Parameters.Add("?", OleDbType.Integer).Value = CInt(SAPSIDTextBox.Text)
cmd.Parameters.Add("?", OleDbType.WChar, 255).Value = EmailTextBox.Text
cmd.Parameters.Add("?", OleDbType.WChar, 255).Value = PhoneTextBox.Text
cmd.Parameters.Add("?", OleDbType.WChar, 255).Value = CollegeComboBox.Text
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Using
It passes through the program fine (finally), however doesn't actually seem to update the database at all. Is there a save command, or a push command I'm missing?
What I'd like is it to take this information and insert it into the table, so if the program closes, it's still in the database.

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

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