I have a program that is Access 2010 front end and a SQL Server database as back end.
I wrote a routine that inserts a record into SQL Server.
Here is the code:
DoCmd.RunSQL "INSERT INTO [dbo_phoneno] (dtstamp, who, what, sortorder, company, typephoneno, name, wphone, cphone, mob) " _
& "VALUES(" _
& "'" & pubDTStamp & "'," _
& "'" & pubWho & "'," _
& "'" & pubWhat & "'," _
& "'" & pubSortOrder & "'," _
& "'" & pubCompany & "'," _
& "'" & pubType & "'," _
& "'" & pubName & "'," _
& "'" & pubWphone & "'," _
& "'" & pubCphone & "'," _
& "'" & pubMob & "') "
The code works fine except when I exit out of the program the record is written out again. I checked the code but do not see where it can be. Does anyone have suggestions?
Either your code gets executed twice or you have a trigger somewhere that does the additional INSERT.
Use Sql Profiler and run a trace. You'll be able to find from where the second INSERT comes from. If it's not from a trigger, then you'll have to set a breakpoint in your app and run it in debug mode.
Related
I have an Access Frontend with a SQL Server backend.
On one of the forms, there is a bit of VBA to keep an "Audit Log" of the changes.
In one procedure there are these 2 bits of code, the first works, but the second gives an error
Working:
sSQL = "DELETE FROM [dbo_EventReport_Audit_Temp_Before];"
CurrentProject.Connection.Execute sSQL
Not working a few lines down:
sSQL = "INSERT INTO [dbo_EventReport_Audit_Temp_Before] (<TABLE COLUMNS>) SELECT <TABLE COLUMNS> FROM [dbo_EventReport] WHERE ((Event_ID)= <EVENT_ID>");"
CurrentProject.Connection.Execute sSQL
So the first statement deletes any records in the table. This works fine, as I've inserted dummy data and stepped through the code and seen it be deleted.
But the second statement causes an error:
Error -2147467259: ODBC--connection to 'EventsDB' failed.
Anyone any idea why the first statement works ok, but the second fails?
Extracting the value of sSQL for the second statement and manually running it through an SQL Query in Access inserts the data into the table.
EDIT:
I didn't want to post the full statement as it's a bit of a monster. But here is is:
sSQL = "INSERT INTO " & sAudTmpTable & " ( [audType], [audDate], [audUser], [Event_Number], [Event_ID], " & _
"[Received_Date], [Response_Date], [Site], [Server], [Workstation], [Software_Version], [Data_Version], " & _
"[Description], [Test_Description], [Company], [Observed_By], [Observed_Date], [Tested_By], [AssignedTo], " & _
"[Tested_Date], [Test_Result], [Ind_Tested_By], [Ind_Tested_On], [Ind_Test_Result], [Reviewed_By], " & _
"[Actioned_Date], [Review_Date], [Review_Result], [Completed_By], [Completed_Date], [Closed_By], " & _
"[Closed_Date], [Exclude], [Category], [State], [Event_Responsibility], [Probability], [WIP_Number], " & _
"[OriginalWIP], [Severity], [Blocked], [Block_Description], [Tags], [Work], [TaskID], [EventType], " & _
"[DefectType], [known_issue_impact], [known_issue_description], [Operator_Notes], [BugWIP], " & _
"[SupplierName], [SupplierCompany], [Simulator], [ATSTest], [FixPriority] ) " & _
"SELECT '" & EditOrInsert & "' AS Expr1, '" & DateTime & "', '" & User & "', [Event_Number], [Event_ID], " & _
"[Received_Date], [Response_Date], [Site], [Server], [Workstation], [Software_Version], [Data_Version], " & _
"[Description], [Test_Description], [Company], [Observed_By], [Observed_Date], [Tested_By], [AssignedTo], " & _
"[Tested_Date], [Test_Result], [Ind_Tested_By], [Ind_Tested_On], [Ind_Test_Result], [Reviewed_By], " & _
"[Actioned_Date], [Review_Date], [Review_Result], [Completed_By], [Completed_Date], [Closed_By], " & _
"[Closed_Date], [Exclude], [Category], [State], [Event_Responsibility], [Probability], [WIP_Number], " & _
"[OriginalWIP], [Severity], [Blocked], [Block_Description], [Tags], [Work], [TaskID], [EventType], " & _
"[DefectType], [known_issue_impact], [known_issue_description], [Operator_Notes], [BugWIP], " & _
"[SupplierName], [SupplierCompany], [Simulator], [ATSTest], [FixPriority] " & _
"FROM [" & sTable & "] WHERE ((" & sKeyField & ")=" & lngKeyValue & ");"
You reported this attempt fails ...
CurrentProject.Connection.Execute sSQL
... but this works using the same sSQL statement ...
CurrentDb.Execute sSQL, dbFailOnError + dbSeeChanges
CurrentProject.Connection.Execute is an ADO method. CurrentDb.Execute is a DAO method. The two methods are similar, but not the same.
One important difference is the ADO version is more likely to fail when the SQL statement includes reserved words as object (table, field, etc.) names; DAO is more forgiving about problem names.
But there are other differences, and it is not possible to determine which of them was the key factor for an INSERT statement we haven't seen. ;-)
I keep getting a syntax error when I run a debug on the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles add.Click
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
'Open Connection if not yet Open
cnn.Open() End If
cmd.Connection = cnn
If Me.sn.Tag & "" = "" Then
cmd.CommandText = "INSERT INTO First_Year(Student_No,Lastname,Firstname,Year_Level,Enroll_Date,SEX,SY,CIVIL_STATUS,Religion,Birthdate,TEL_NO,Father,Occupation_F,Mother,Occupation_m,School Last Attended,Address School,Middle_Name)" +
"VALUES ('" & Me.sn.Text & "','" & Me.fn.Text & "','" & Me.ln.Text & "' ,'" & Me.Year.Text & "','" & Me.ed.Value & "','" & Me.s.Text & "','" & Me.sy.Text & "','" & Me.cs.Text & "','" & Me.re.Text & "'," & Me.cn.Text & ",'" & Me.bd.Value & "','" & Me.fa.Text & "','" & Me.fo.Text & "','" & Me.ma.Text & "','" & Me.mo.Text & "','" & Me.lad.Text & "','" & Me.ad.Text & "','" & Me.mi.Text & "')"
cmd.ExecuteNonQuery()
Can some please point out to me whats wrong with it?
You have some fields name that contains spaces. To use these fields names you need to enclose them in square brackets
cmd.CommandText = "INSERT INTO First_Year " & _
"(Student_No,Lastname,Firstname,Year_Level,Enroll_Date,SEX, " & _
"SY,CIVIL_STATUS,Religion,Birthdate,TEL_NO,Father,Occupation_F,Mother, " &
"Occupation_m,[School Last Attended],[Address School],Middle_Name) " &
"...... "
Said that, remember that string concatenations like yours lead to Sql Injection and problem in parsing strings that contains quotes (O'Brien) or decimal numbers or date
Search about Sql Injection and Parameterized queries
A parameterized approach to your query would be
cmd.CommandText = "INSERT INTO First_Year " & _
"(Student_No,Lastname,Firstname,Year_Level,Enroll_Date,SEX, " & _
"SY,CIVIL_STATUS,Religion,Birthdate,TEL_NO,Father,Occupation_F,Mother, " &
"Occupation_m,[School Last Attended],[Address School],Middle_Name) " &
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
cmd.Parameters.AddWithValue("#p1", Me.sn.Text)
cmd.Parameters.AddWithValue("#p2", Me.fn.Text)
... and so on for the remainder 16 parameters placeholders
... respecting their position and converting to the appropriate datatype
you need to remove the space here (in your query) :
......School Last Attended,Address School.......
or write it like this :
..........[School Last Attended],[Address School]..........
The above error is being thrown when I run the below command:
CurrentDb.Execute "INSERT INTO Table2(FirstName, LastName)" & "VALUES('" & Me.frst_Name_txt & ", '" & Me.lst_Name_txt & "','" & "')"
Can anyone see where I am going wrong?
Thanks
The error:
You have extra value '" & "' and also Text data types require delimiters around the value. At its simplest an apostrophe.
Try this
CurrentDb.Execute "INSERT INTO Table2(FirstName, LastName)" & "VALUES('" & Me.frst_Name_txt & "','" & Me.lst_Name_txt & "')"
You're missing an apostrophe: CurrentDb.Execute "INSERT INTO Table2(FirstName, LastName) VALUES('" & Me.frst_Name_txt & "', '" & Me.lst_Name_txt & "')"
I have a form which writes data to a linked SQL table, and one of the functions is an EDIT function, but when I make the edits and resubmit the data I get the error
Run Time Error 3073 Operation Must Use an Updateable Query
I have used this code before on normal Access tables housed in the database where the form is and it works fine, do I need to make some alterations to the code since it is editing the data on a linked SQL table? The code is as follows?
CurrentDb.Execute "UPDATE dbo_AC_CD_Data_Form " & _
"SET EmployeeID='" & Me.txtEmpID & "'" & _
", EmployeeName='" & Me.txtEmpName & "'" & _
", Gender='" & Me.cboGender & "'" & _
", EEOC='" & Me.cboEEOC & "'" & _
", ReadinessLevel='" & Me.cboReadyLvl & "'" & _
", Division='" & Me.cboDivision & "'" & _
", Center='" & Me.txtCenter & "'" & _
", EmployeeFeedback='" & Me.txtFeedback & "'" & _
", DevelopmentForEmployee='" & Me.txtDevelopment & "'" & _
", Justification='" & Me.txtJustification & "'" & _
", Changed ='" & Me.cboChanged & "'" & _
" WHERE EmployeeID='" & Me.txtEmpID & "'"
Delete the linked table in Access and link it again. The wizard should ask to you for a primary key. Select the field or fields that compound the primary key.
Note that is not necessary that the original table have a pk (This is usually happen linking views).
I'm working with an SQL Server and I'm create a program to add records to the database. However, the database's field for the Dates of Births isn't being accepted.
At the server side, the data type is 'Date' on MS Express SQL Server that should be YYYY-MM-DD. However, when trying to 'upload' the new records from the program the dates are being rejected. I know it's down to how I'm formatting them and particularly I know it's literally just two lines of code; But I can't get it going!
SQL = "Insert into PersonsA(Members_ID," & _
"Gamer_Tag," & _
"Screenname," & _
"First_Name," & _
"Last_Name," & _
"DoB," & _
"E_Mail_Address," & _
"Position," & _
"U_G_Studio," & _
"Cautions," & _
"Record," & _
"Event_Attendance," & _
"Member_Status) values('" & Me.midtxt.Text.Trim & "'," & _
"'" & Me.gttxt.Text.Trim & "'," & _
"'" & Me.sntxt.Text.Trim & "'," & _
"'" & Me.fntxt.Text.Trim & "'," & _
"'" & Me.lntxt.Text.Trim & "'," & _
"" & Val(Me.dobtxt.Text) & "" & _ 'THIS IS THE DATES OF BIRTHS
"'" & Format(Me.dobtxt.Text, "YYYY-MM-DD") & "'," & _ 'THIS IS FORMATTING
"'" & Me.emailtxt.Text.Trim & "'," & _
"'" & Me.teamptxt.Text.Trim & "'," & _
"'" & Me.ugptxt.Text.Trim & "'," & _
"'" & Me.ugctxt.Text.Trim & "'," & _
"'" & Me.recordtxt.Text.Trim & "'," & _
"'" & Me.eventatxt.Text.Trim & "'," & _
"'" & Me.Mstattxt.Text.Trim & "')"
So as you can see the two lines I'm having trouble are:
"" & Val(Me.dobtxt.Text) & "" & _
"'" & Format(Me.dobtxt.Text, "YYYY-MM-DD") & "'," & _
I know it'll be something really stupid, but I'm newish to programming.
Reject your command string and start using SqlParameter.
Dim conn As New SqlConnection("conStr")
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = "INSERT INTO [PersonsA] ([Members_ID], [Gamer_Tag]) VALUES (#Members_ID, #Gamer_Tag);"
cmd.Parameters.AddWithValue("#Members_ID", Me.midtxt.Text.Trim) '<- If Int type change to: Integer.Parse(Me.midtxt.Text.Trim)
cmd.Parameters.AddWithValue("#Gamer_Tag", Me.gttxt.Text.Trim)
conn.Open()
cmd.ExecuteNonQuery()
Date column example:
cmd.Parameters.AddWithValue("#MY_DATE_PARAM", Date.Parse(Me.dateTextBox.Text.Trim))