Run time 3134 error MS Access SQL - sql

Private Sub AddItemButton_Click()
Dim db As Database
Set db = CurrentDb
Dim Item As String
Dim Rate As String
Dim AltRate As String
Dim Reason As String
Dim ApporvedBy As String
Dim Company As String
Dim JobID As String
Me.JobID2 = Me.JobID
db.Execute "INSERT INTO InvItemsRecords (Item, Rate, AltRate, Reason, ApprovedBy, Company, JobID) VALUES ('" & Me.ItemAppendCBO & "', " & Me.RateAppend & ", " & Me.AltRateAppend & ", '" & Me.ReasonAppend & "', '" & Me.ApprovedByAppend & "', '" & Me.Customer & "', " & Me.JobID2 & ")"
Me.AltRate2.Value = Null
End Sub

You should use string literals for your Queries
Dim sqlQuery As String
sqlQuery = "INSERT INTO InvItemsRecords (Item, Rate, AltRate, Reason, ApprovedBy, " & _
"Company, JobID) VALUES ('" & Me.ItemAppendCBO & "', " & Me.RateAppend & ", " & Me.AltRateAppend & ", '" & Me.ReasonAppend & "', '" & _
Me.ApprovedByAppend & "', '" & Me.Customer & "', " & Me.JobID2 & ")"
db.Execute sqlQuery
It makes it a lot easier to debug
INSERT INTO InvItemsRecords (Item, Rate, AltRate, Reason, ApprovedBy, Company, JobID)
VALUES('Some Item', 100, 343, 'Reason A', 'John', 'Jane Doe', Null)
Chances are you are inadvertently passing 1 or more null values to non-nullable fields. Also be careful about the data types. You may need to use CStr(), CInt(), CLong, CDate() or ... to cast your data into the right format If a field can be left blank us NZ().
NZ(Me.RateAppend, True)

Related

Access 2016 Run time error invalid use of null

I am checking to see if a record exists in a Access 2016 form if it exist show a message if not add it to the database. But I am getting a invalid use of null when txtRepGrpNumber is empty, if not empty it adds it even though it already exists in the database. RepGrpNumber is a numeric field in the database. It errors out on my if statment.
Private Sub btnSave_Click()
Dim db As DAO.Database
Dim strSql As String
Dim message As String
Set db = CurrentDb
If Nz(CStr(Me.txtRepGrpNumber)) >= "" Then
strSql = "INSERT INTO dbo_TblSwShowRoom(RepGrpNumber, ViewOrder, RepCompany, AddressFull, Contact, Phone, Hours, ViewPhotos, ViewTour, ImageShow, Image, AddBy, DateAdded, DateChanged, ChangedBy, Enabled) " & _
"VALUES('" & Me.txtRepGrpNumber & "','" & Me.txtViewOrder & "', '" & Me.txtRepCompany & "', '" & Me.txtAddressFull & "', '" & Me.txtContact & "', '" & Me.txtPhone & "', '" & Me.txtHours & "', '" & Me.txtViewPhotos & "', '" & Me.txtViewTour & "', '" & Me.txtImageShow & "', '" & Me.txtImage & "', '" & Me.txtAddBy & "', '" & Me.txtDateAdded & "', '" & Me.txtDateChanged & "', '" & txtChangedBy & "', '" & txtEnabled & "')"
db.Execute strSql
Me.SubFrmSwShowRoom.Requery
Else
message = MsgBox("Cannot save because Group Number is Blank", vbCritical)
End If
'End If
Me.Requery
End Sub
If CStr(Nz(Me.txtRepGrpNumber,"")) <> "" Then
CStr can't convert a Null value. CStr(Null) throws the same error you're getting. This should do:
If Nz(Me.txtRepGrpNumber, vbNullString) <> vbNullString Then
The reason you are getting invalid use of null is if the value of txtRepGrpNumber has not been changed since you opened the form, and it was null, CStr throws the error invalid use of null when it gets to that.
To fix it:
If Me.txtRepGrpNumber & vbNullString <> vbNullString Then

Run-time Error 3075 in MS Access while appending email distribution to table via SQL

I have the following function defined in MS Access VBA:
Function SendToEMail(iTo As String, iFrom As String, icc As String, ibcc As String, iSubject As String, iBody As String, iSystem As String, iAttachments As String)
strSQL = "INSERT INTO tblEmail ([To], [From], [CC], [BCC], [Subject], [Body], [Create_Time], [System], [Attachments]) IN '\\ahmtroy03\Email.accdb' VALUES ('" & iTo & "', '" & iFrom & "', '" & icc & "', '" & ibcc & "', '" & iSubject & "', '" & iBody & "', #" & Now() & "#, '" & iSystem & "', '" & iAttachments & "');"
DoCmd.RunSQL strSQL
End Function
This function inserts records into a table. Each record is an email. When appending to this table, I get error 3075 and it references the [To] field. I've changed some info for privacy. All other distributions come through okay but THIS one doesn't make it.
firstname.last-name#something-corporation.com, firstname.last-name#something-corporation.com, firstname.lastname#something-corporation.com, firstname.lastname#something-corporation.com, firstname.lastname#something-corporation.com, firstname.lastname#something-corporation.com

Insert SQL from combobox/textbox selections

I'm trying to add a row of data into the table using the selections from comboboxes and the textlabel. The error I'm receiving is in regard to the insert statement. Is this the correct way to reference the values in a combobox or textbox? I'm inserting into a table that has an autonumber primary key. Any help would be greatly appreciated.
Private Sub addResult_Click()
Dim strSQL As String
strSQL = "INSERT INTO Results (Student_ID, Class_ID, Test_Type, Student_Score, Total_Score, Level)
VALUES ('" & Me.cboStudents.Column(0) & "',
'" & Me.cboTeacher.Column(0) & "',
'" & Me.cboTestType.Column(1) & "',
'" & Me.txtTotalScore.Value & "',
'" & Me.txtStudentScore.Value & "',
'" & Me.cboTeacher.Column(2) & "')"
CurrentDb.Execute strSQL
End Sub

How to ignore the Null values in Insert query in access

I have the Database table where the Table needs to be updated using a form.
However all the fields in the Form need not be mandatory to be filled.
I am Writing the Below VB code for inserting However I get an error stating that there is a syntax error in the statement.As i understand it is because of the Null Values in the Variable. I understand that I need to use DBNull.Value for all the null Values.
Here the Thing is there are too many fields to check if the value is null or not.
any body suggest if there is a way to do a mass check on the values entered to be null?
VBCode:
Dim StrSQL As String
Dim StrSQL1 As String
Dim tktID As Variant
Dim Assi As Variant
Dim reopened As Variant
Dim valid As Variant
Dim Reopenreason As Variant
Dim ReassignmentAG As Variant
Dim RBSCollab As Variant
Dim SMEconf As Variant
Dim Cloabag As Variant
Dim smeName As Variant
Dim Updat As Variant
Dim Closed As Variant
Dim iss As Variant
Dim ana As Variant
Dim res As Variant
Dim rVariant As Variant
' Assigining values
tktID = Ticket_number.Value
reopened = Ticket_Reopened.Value
valid = Valid_Reopen.Value
Assi = Assiginee.Value
Reopenreason = Reopen_reason.Value
ReassignmentAG = Reassignment_AG.Value
RBSCollab = RBS_Collab.Value
SMEconf = CkBxSMEConfirmation.Value
Cloabag = Collabarated_AG.Value
smeName = SME_Name.Value
Updat = Update.Value
Closed = Issue_Closed.Value
iss = Issue.Value
ana = Analysis.Value
res = Resolution.Value
rdate = Resolve_date.Value
'Insert values into the tables
StrSQL = "INSERT INTO Updates (TicketID,Assiginee,ReassignmentAG,RBSCollab,CollabAG,SMEconfirmation,SMEName,Update,IssueClosed,Issue,Analysis,Resolution,ResolveDate,TicketReopened,ValidReopen,ReopenReason) VALUES ('" & tktID & "','" & Assi & "','" & ReassignmentAG & "','" & RBSCollab & "','" & Cloabag & "','" & SMEconf & "','" & smeName & "','" & Updat & "','" & Closed & "','" & iss & "','" & ana & "','" & res & "','" & rdate & "','" & reopened & "','" & valid & "','" & Reopenreason & "' ) "
DoCmd.RunSQL StrSQL
thanks in advance for your help
I, too, setup my first Access database using lots of unbound controls and SQL statements for moving data around. But this is not the way to use Access. You should be using bound forms where the controls automatically know what the constraints are based on the table/columns they are bound to.
This means much less code for you to write (and maintain), future developers can look at your Access app and know what's going on because it will be done in the Access paradigm, and if you place as much logic into your tables/relationships as possible then if someone comes along and links to your ACCDB or opens the backend they could enter data without entering bad data.
So ultimately this is an XY problem. Get rid of all this code (especially DoCmd.RunSQL) and create a bound form. Put your validation logic in foreign keys, validation rules, and/or data macros in the table.
A simple solution to this problem could be just check for element's value before using in the inset query and if element's value is undefined than set with null.
Pass this value to database in the query.
Do this for each field:
tktID = IIF(ISNULL(Ticket_number.Value),"Null","'" & Ticket_number.Value & "'")
Then instead of this:
VALUES ('" & tktID & "',...
Do this
VALUES (" & tktID & ",...
Or if you don't mind replacing nulls with empty strings:
tktID = Nz(Ticket_number.Value)
will do it.
Of course you should at least make sure no single quotes are in the stings, so even better:
tktID = IIF(ISNULL(Ticket_number.Value),"Null","'" & Replace(Ticket_number.Value,"'","''") & "'")
After building the string for INSERT statment
strSql = "INSERT INTO tblmovimentiServizi ( msid, " _
& " msData, msIdDestinazione, msOraInizioServizio, msOraFineServizio, msAndataRitorno, " _
& " msOraVincoloEntrata, msOraVincoloUscita, msidAnagraficaAutomezzi, msServizioEseguito, msNoteCommenti) " _
& " VALUES ('" & rst!newid & "', #" & rst!msData + Me.g1 & "#, '" _
& rst!msIdDestinazione & "', #" _
& rst!msOraInizioServizio & "#, #" _
& rst!msOraFineServizio & "#, '" _
& rst!msAndataRitorno & "', #" _
& rst!msOraVincoloEntrata & "#, #" _
& rst!msOraVincoloUscita & "#, '" _
& rst!msidAnagraficaAutomezzi & "', " _
& eseguito & ", '" _
& rst!msNoteCommenti & "'" _
& ");"
I added
strSql = Replace(strSql, "''", "null")
strSql = Replace(strSql, "##", "null")
and it works.

How to insert customer details into Orders table

I have an assignment to build a basic database driven e-commerce site. I have a home page, a products page, an orders page, an order confirm page, a shopping cart page and a view current orders page. The site uses an Access database with three tables.
A Customer table, with all of the customer details, (FirstName, LastName, EmailAdd, CardNo, CardEx, SortCode, DeliveryAdd, Postcode)
A Products table, with all the product information, (ProductID, ProductName, Price, ProductType, Images, ProductDescription).
And an Orders table which contains CustomerID and ProductID.
I'm trying to create an INSERT statement on the orders page so that when the customer inserts their details and presses the submit button the customers table will have a new record inserted. I also want this to create an entry in the orders table and redirect the client to the order confirm page which will display the details of the order.
Here is my code which runs when the submit button is clicked on the order form.
EDIT I've fixed the error with the missing apostrophe. Attempting to insert using two sql commands as I've been told that access databases can't handle two at once. Still getting an error though.
Protected Sub btnAddRecord_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim strFirstName As String
Dim strLastName As String
Dim strEmailAdd As String
Dim intCardNo As String
Dim strCardEx As String
Dim intSortCode As String
Dim strDeliveryAdd As String
Dim strPostCode As String
Dim intProductID As Integer
strFirstName = tbxFirstName.Text
strLastName = tbxLastName.Text
strEmailAdd = tbxEmailAdd.Text
intCardNo = tbxCardNo.Text
strCardEx = tbxCardEx.Text
intSortCode = tbxSortCode.Text
strDeliveryAdd = tbxDeliveryAdd.Text
strPostCode = tbxPostcode.Text
intProductID = ddlProduct.SelectedValue
Dim strDatabaseNameAndLocation As String
strDatabaseNameAndLocation = Server.MapPath("KingToots.mdb")
Dim strSQLCommand As String
strSQLCommand = "INSERT INTO Customer(FirstName, LastName, EmailAdd, CardNo, CardEx, SortCode, DeliveryAdd, Postcode) " & _
"Values ('" & strFirstName & "', '" & strLastName & "', '" & strEmailAdd & "', '" & intCardNo & "', '" & strCardEx & "', '" & intSortCode & "', '" & strDeliveryAdd & "', '" & strPostCode & "');"
Dim objOleDbConnection As System.Data.OleDb.OleDbConnection
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
Dim objOleDbCommand As System.Data.OleDb.OleDbCommand
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
objOleDbCommand.ExecuteNonQuery()
objOleDbConnection.Close()
strSQLCommand = "INSERT INTO Orders(ProductID) " & "Values ('" & intProductID & "');"
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
objOleDbCommand.ExecuteNonQuery()
objOleDbConnection.Close()
strSQLCommand = "SELECT Customer.* FROM Customer ORDER BY Customer.CustomerID DESC;"
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
Dim objOleDbDataReader As System.Data.OleDb.OleDbDataReader
objOleDbDataReader = objOleDbCommand.ExecuteReader()
Dim datDataTable As System.Data.DataTable
datDataTable = New System.Data.DataTable()
datDataTable.Load(objOleDbDataReader)
objOleDbConnection.Close()
tbxFirstName.Text = ""
tbxLastName.Text = ""
tbxEmailAdd.Text = ""
tbxCardNo.Text = ""
tbxCardEx.Text = ""
tbxSortCode.Text = ""
tbxDeliveryAdd.Text = ""
tbxPostcode.Text = ""
End Sub
You're missing the closing quotes at the end of this line:
strSQLCommand = "INSERT INTO Customer(FirstName, LastName, EmailAdd, CardNo, CardEx, SortCode, DeliveryAdd, Postcode) " & _
"Values ('" & strFirstName & "', '" & strLastName & "', '" & strEmailAdd & "', '" & intCardNo & "', '" & strCardEx & "', '" & intSortCode & "', '" & strDeliveryAdd & "', '" & strPostCode & ");"
About the obvious SQL injection problem, switching to parameters would be the best way to do it (and you'd never have your original issue if you did, parameters don't use quotes), but at the very least run a replace on your strings to replace ' with '' so your program doesn't just die if you get a customer called O'Neil.
He is correct, you don't want to do this you will get sql injection. But here is the solution to your problem anyway.
The problem is not in the last sql statement but in the previous one.
'" & strPostCode & " is missing the last single quote.
it should read:
'" & strPostCode & "');