I'm using this insert statement in my code in vba excel but i'm not able to break it into more than one line
SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & " _
,'" & txtContractStartDate.Value & "' _
,'" & txtSeatNo.Value & "' _
,'" & txtFloor.Value & "','" & txtLeaves.Value & "')"
It is giving error "Expected end of statement". Plz help.
You cannot use the VB line-continuation character inside of a string.
SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & _
"','" & txtContractStartDate.Value & _
"','" & txtSeatNo.Value & _
"','" & txtFloor.Value & "','" & txtLeaves.Value & "')"
you may simply create your string in multiple steps, a bit redundant but it keeps the code readable and maintain sanity while debugging or editing
SqlQueryString = "Insert into Employee values("
SqlQueryString = SqlQueryString & txtEmployeeNo.Value & " ,"
SqlQueryString = SqlQueryString & " '" & txtEmployeeNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtContractStartDate.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtSeatNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtContractStartDate.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtSeatNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtFloor.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtLeaves.Value & "' )"
If the long string to multiple lines confuses you. Then you may install mz-tools addin which is a freeware and has the utility which splits the line for you.
Download Mz-tools
If your string looks like below
SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & "','" & txtContractStartDate.Value & "','" & txtSeatNo.Value & "','" & txtFloor.Value & "','" & txtLeaves.Value & "')"
Simply select the string > right click on VBA IDE > Select MZ-tools > Split Lines
Related
In access 2016 I'm trying to use an update command.I'm creating a database as my internship project as I'm unfamiliar with the coding I have been struggling a lot. I'm referring to a video by Setha Iech: https://www.youtube.com/watch?v=Ri2Y9-16AEo. When I'm using the below code an error continuously pops up
Error 3464
Private Sub cmdAdd_Click()
'when we click on button Add there are two options
'1. for insert
'2. for update
If Me.txtID.Tag & "" = "" Then
'this is for insert new
'add data to table
CurrentDb.Execute "INSERT INTO Business(ID, Project_ID, [Date_of_Enquiry], Division, Client, Description, Probability_to_win,Status, [Proposal_Submission_date], [Expected_award_date], Remarks)" & _
"VALUES ('" & Me.txtID & "','" & Me.txtProject_ID & "','" & Me.txtDate_of_Enquiry & "','" & Me.cboDivision & "','" & _
Me.txtClient & "','" & Me.txtDescription & "','" & Me.cboProbability_to_win & "','" & Me.cboStatus & "','" & Me.txtProposal_Submission_date & "','" & Me.txtExpected_award_date & "','" & Me.txtRemarks & "')"
Else
'otherwise (Tag of txtID store the ID of statement to be modified)
CurrentDb.Execute "UPDATE Business" & _
" SET ID=" & Me.txtID & _
", Project_ID='" & Me.txtProject_ID & "'" & _
", Date_of_Enquiry='" & Me.txtDate_of_Enquiry & "'" & _
", Division='" & Me.cboDivision & "'" & _
", Client='" & Me.txtClient & "'" & _
", Description='" & Me.txtDescription & "'" & _
", Probability_to_win='" & Me.cboProbability_to_win & "'" & _
", Status='" & Me.cboStatus & "'" & _
", Proposal_Submission_date='" & Me.txtProposal_Submission_date & "'" & _
", Expected_award_date='" & Me.txtExpected_award_date & "'" & _
", Remarks='" & Me.txtRemarks & "'" & _
" WHERE ID=" & Me.txtID.Tag
End If
'clear form
cmdClear_Click
'refresh data in list on form
databasesub.Form.Requery
End Sub
Thank you for your answers in advance
what is wrong in this code i get syntax error from this query
ssql = "UPDATE karakter SET lvl='" & Form1.Label7.Caption & "','" & hp = Form1.Label18.Caption & "','" & mp = Form1.Label17.Caption & "','" & para = Form1.Label19.Caption & "','" & yuzde = Form1.Label16.Caption & "' WHERE id='" & Form1.Label5.Caption & "'"
You have wrong positions for you quotes.
ssql = "UPDATE karakter SET lvl='" & Form1.Label7.Caption & "', " & _
"hp ='" & Form1.Label18.Caption & "', " & _
"mp ='" & Form1.Label17.Caption & "', " & _
"para ='" & Form1.Label19.Caption & "', " & _
"yuzde ='" & Form1.Label16.Caption & "' " & _
"WHERE id='" & Form1.Label5.Caption & "'"
I suggest to use the parameters instead of concatenation.
I input the Right dataSource but it didnt i cant fixed the problem cmd.ExecuteNonQuery()
saying:
Syntax error in INSERT INTO statement.
Code:
Private Sub btnadd1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnadd1.Click
Dim cmd As New OleDb.OleDbCommand
Dim Printlist1 As New DataTable
If Not con.State = ConnectionState.Open Then
con.ConnectionString = "Provider=Microsoft.Ace.OLEDB.12.0; Data Source=c:Database11.accdb"
con.Open()
cmd.Connection = con
End If
If Me.text1.Tag & "" = "" Then
cmd.CommandText = "INSERT INTO Printlist1(StickerCode, Description, Company, Department, Location, User, SerialNumber, DatePurchased, Tagable, Quantity, Brand, Model)" & _
" VALUES(" & Me.text1.Text & ",'" & Me.text2.Text & "','" & _
Me.text3.Text & "','" & Me.text4.Text & "','" & Me.text5.Text & "','" & _
Me.text6.Text & "','" & Me.text7.Text & "','" & Me.text8.Text & "','" & _
Me.text9.Text & "','" & Me.text10.Text & "','" & Me.text11.Text & "','" & _
Me.text12.Text & "')"
cmd = New OleDbCommand(cmd.CommandText, con)
cmd.ExecuteNonQuery()
Else
cmd.CommandText = "UPDATE Printlist1 " & _
" SET StickerCode='" & Me.text1.Text & _
", Description='" & Me.text2.Text & "'" & _
", Company='" & Me.text3.Text & "'" & _
", Department='" & Me.text4.Text & "'" & _
", Location='" & Me.text5.Text & "'" & _
", User='" & Me.text6.Text & "'" & _
", SerialNumber='" & Me.text7.Text & "'" & _
", DatePurchased='" & Me.text8.Text & "'" & _
", Tagable='" & Me.text9.Text & "'" & _
", Quantity='" & Me.text10.Text & "'" & _
", Brand='" & Me.text11.Text & "'" & _
", Model='" & Me.text12.Text & "'" & _
" WHERE text1=" & Me.text1.Tag
cmd.ExecuteNonQuery()
End If
RefreshData()
Me.btnclear1.PerformClick()
con.Close()
End Sub
Use a parameterized query, like this:
cmd.CommandText = "INSERT INTO Printlist1(StickerCode, Description, Company, Department, Location, User, SerialNumber, DatePurchased, Tagable, Quantity, Brand, Model)" & _
" VALUES(#StickerCode, #Description, #Company, #Department, #Location, #User, #SerialNumber, #DatePurchased, #Tagable, #Quantity, #Brand, #Model)"
cmd.Parameters.AddWithValue("#StickerCode", Me.Text1.Text)
cmd.Parameters.AddWithValue("#Description", Me.Text2.Text)
cmd.Parameters.AddWithValue("#Company", Me.Text3.Text)
cmd.Parameters.AddWithValue("#Department", Me.Text4.Text)
cmd.Parameters.AddWithValue("#Location", Me.Text5.Text)
cmd.Parameters.AddWithValue("#User", Me.Text6.Text)
cmd.Parameters.AddWithValue("#SerialNumber", Me.Text7.Text)
cmd.Parameters.AddWithValue("#DatePurchased", Me.Text8.Text)
cmd.Parameters.AddWithValue("#Tagable", Me.Text9.Text)
cmd.Parameters.AddWithValue("#Quantity", Me.Text10.Text)
cmd.Parameters.AddWithValue("#Brand", Me.Text11.Text)
cmd.Parameters.AddWithValue("#Model", Me.Text12.Text)
Note: It is best to keep the order of the parameters in line with the query, as databases like Microsoft Access will not execute the query correctly if the order is altered.
It is likely that one of your Me.textN.Text values has an apostrophe in it or some other unexpected character that is breaking your SQL quotes. The solution to this is to use parametized queries and/or stored procedure instead.
This incidentally, will also protect you form the SQL Injection attacks that take advantage of the same shortcoming in composing SQL commands as strings in the client application.
(NOTE: I am assuming the Me.text1.Text as the StickerCode is a number. Otherwise that's the problem as you are not quoting it the way you do with the other columns.)
First line is missing as '
...
"SET StickerCode='" & Me.text1.Text & "'" & _
...
You are missing single quotes around your first value. Try
" VALUES('" & Me.text1.Text & "','" & Me.text2.Text & "','" & _
Me.text3.Text & "','" & Me.text4.Text & "','" & Me.text5.Text & "','" & _
Me.text6.Text & "','" & Me.text7.Text & "','" & Me.text8.Text & "','" & _
Me.text9.Text & "','" & Me.text10.Text & "','" & Me.text11.Text & "','" & _
Me.text12.Text & "')"
following is the code which is use to enter datagridview items into the table.
Dim X As DataGridViewRow
grnno = 123123
glocation = txtlocation.Text
gsupplier = txtsupplier.Text
greceivedby = txtreceivedby.Text
greceiveddate = txtreceiveddate.Text
grn_status = cmbstatus.SelectedItem
ggrossamt = txtgrossamt.Text
gdiscountamount = txtdiscount.Text
gtotalnetamount = txttotalnet.Text
sqlstr = "INSERT INTO POS_GRN_HDR(loc_code,supplier_code,created_by,created_Date,grn_status,gross_amt,disc_Amt,net_Amt) values('" & glocation & "','" & gsupplier & "','" & greceivedby & "','" & greceiveddate & "','" & grn_status & "'," & ggrossamt & "," & gdiscountamount & "," & gtotalnetamount & " )"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.ExecuteNonQuery()
For Each X In datagridItems.Rows
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) VALUES('" & grnno & "','" & X.Cells(0).Value & "','" & X.Cells(1).Value & "','" & X.Cells(2).Value & "','" & X.Cells(3).Value & "','" & X.Cells(4).Value & "','" & X.Cells(5).Value & "','" & X.Cells(6).Value & "','" & X.Cells(7).Value & "' ,'" & X.Cells(8).Value & "','" & X.Cells(9).Value & "','" & X.Cells(10).Value & "')"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.ExecuteNonQuery()
Next
the error is in the 2nd insert statement, it gives error cannot convert string to integer.. the cells from x.cell(6) are of integer type and in database also its integer type, now I want to ask should I enclose it in single quotations or not, as enclosing in single quotations give such errors like syntax '' and in double quotations it gives like cannot convert string to int type.please tell where I am doing wrong.
First of all use parametrized queries! It is safer and also more readable. You are passing some value as string but should be integer.
sqlstr = "INSERT INTO POS_GRN_HDR(loc_code,supplier_code,created_by,created_Date,grn_status,gross_amt,disc_Amt,net_Amt) _
values(#glocation, #gsupplier, #greceivedby, #greceiveddate, #grn_status, #ggrossamt, #gdiscountamount, #gtotalnetamount)"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.Parameters.AddWithValue("#glocation", glocation)
sqlcmd.Parameters.AddWithValue("#gsupplier", gsupplier) //and so on
For Each X In datagridItems.Rows
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) _
VALUES(#grnno, #item_code, #description, ...)"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.Parameters.AddWithValue("#grnno", grnno)
sqlcmd.Parameters.AddWithValue("#item_code", CType(X.Cells(0).Value, Integer)) //cast to proper type
sqlcmd.ExecuteNonQuery()
Next
Remove the single quote marks ''
For example (and referring only to x.cell(6) as per your post) use " & X.Cells(6).Value & "
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) VALUES('" & grnno & "','" & X.Cells(0).Value & "','" & X.Cells(1).Value & "','" & X.Cells(2).Value & "','" & X.Cells(3).Value & "','" & X.Cells(4).Value & "','" & X.Cells(5).Value & "', " & X.Cells(6).Value & ",'" & X.Cells(7).Value & "' ,'" & X.Cells(8).Value & "','" & X.Cells(9).Value & "','" & X.Cells(10).Value & "')"
You may also need to cast it (assuming it's always going to have a numeric value)
" & CInt(X.Cells(6).Value) &"
I will assume you know of SQL injection and this method of updating a database is generally 'outdated' and 'bad practice' now and you should use parameters instead...
Updated
Since there is a possibility of a null (and you want it to be a 0 where this is the case), you could use something like (not tested as I'm not a VB person)
dim cellSix as integer
if IsNothing(X.Cells(6).Value then
cellSix = 0
else
cellSix = CInt(X.Cells(6).Value)
end if
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) VALUES('" & grnno & "','" & X.Cells(0).Value & "','" & X.Cells(1).Value & "','" & X.Cells(2).Value & "','" & X.Cells(3).Value & "','" & X.Cells(4).Value & "','" & X.Cells(5).Value & "', " & cellSix & ",'" & X.Cells(7).Value & "' ,'" & X.Cells(8).Value & "','" & X.Cells(9).Value & "','" & X.Cells(10).Value & "')"
Or, to keep the code shorter you could use the IIF
cellSix = IIf(isnothing(CInt(X.Cells(6).Value)), 0, CInt(X.Cells(6).Value))
I am totally new to Microsoft Access and VB, what i am trying to do is i have a form with unbounded textboxes which i would like upon clicking a button save the text in each textbox in its unique field.
I managed to write this piece of code with some help from online resources but it keeps giving me syntax error, if someone could point me into the correct way.
CurrentDb.Execute "INSERT INTO UserInformation(" & _
"FirstName, LastName, Company, JobTtile, PhoneNumber, Mobile, Email, Fax, " & _
"IT-DEC-MAKER-FNAME, IT-DEC-MAKER-LNAME) " & _
"VALUES('" & Me.qfirstname & "','" & Me.qlastname & "','" & Me.qcompany & "','" & _
Me.qjob & "','" & Me.qphone & "','" & Me.qmobile & "','" & Me.qemail & "','" & _
Me.qfax & "','" & Me.qitfirstname & "','" & Me.qitlastname & "');"
Since are IT-DEC-MAKER-FNAME and IT-DEC-MAKER-LNAME are invalid identifiers in SQL, you must enclose them in brackets ([ ])
CurrentDb.Execute "INSERT INTO UserInformation(" & _
"FirstName, LastName, Company, JobTtile, PhoneNumber, Mobile, Email, Fax, " & _
"[IT-DEC-MAKER-FNAME], [IT-DEC-MAKER-LNAME]) " & _
"VALUES('" & Me.qfirstname & "','" & Me.qlastname & "','" & Me.qcompany & "','" & _
Me.qjob & "','" & Me.qphone & "','" & Me.qmobile & "','" & Me.qemail & "','" & _
Me.qfax & "','" & Me.qitfirstname & "','" & Me.qitlastname & "');"
UPDATE:
I have two nice helper functions for this kind of things.
This one replaces placeholders in a string with values
Function Build(ByVal s As String, ParamArray args()) As String
' Build("LastName = {0}, FirstName = {1}","Dow","John") --> "LastName = Dow, FirstName = John".
' "\n" will be converted to vbCrLf.
Dim i As Long
s = Replace(s, "\n", vbCrLf)
For i = 0 To UBound(args)
s = Replace(s, "{" & i & "}", Nz(args(i)))
Next i
Build = s
End Function
This one converts a variant value supposed to contain a text in to a SQL value
Public Function SqlStr(ByVal v As Variant) As String
' NULL Returns: NULL
' "" Returns: NULL
' "abc" Returns: 'abc'
' "x'y" Returns: 'x''y'
Dim s As String
s = Nz(v)
If s = "" Then
SqlStr = "NULL"
Else
SqlStr = "'" & Replace(s, "'", "''") & "'"
End If
End Function
You can then use them like this making your code safer and easier to understand.
Dim template As String, sql As String
template = "INSERT INTO UserInformation(" & _
"FirstName, LastName, Company, JobTtile, PhoneNumber, Mobile, Email, Fax, " & _
"[IT-DEC-MAKER-FNAME], [IT-DEC-MAKER-LNAME]) " & _
"VALUES({0},{1},{2},{3},{4},{5},{6},{7},{8},{9});"
sql = Build(template, _
SqlStr(Me.qfirstname), SqlStr(Me.qlastname), _
SqlStr(Me.qjob), SqlStr(Me.qphone), _
SqlStr(Me.qmobile), SqlStr(Me.qemail), _
SqlStr(Me.qfax), SqlStr(Me.qitfirstname), _
SqlStr(Me.qitlastname))
CurrentDb.Execute sql
I suggest you lay out your code like so:
sSQL = "INSERT INTO UserInformation(" _
& "FirstName, LastName, Company, JobTtile, " _
& "PhoneNumber, Mobile, Email, Fax, " _
& "IT-DEC-MAKER-FNAME, IT-DEC-MAKER-LNAME) " _
& "VALUES('" _
& Me.qfirstname & "','" & Me.qlastname & "','" & Me.qcompany & "','" & Me.qjob _
& "','" & Me.qphone & "','" & Me.qmobile & "','" & Me.qemail & "','" & Me.qfax _
& "','" & Me.qitfirstname & "','" & Me.qitlastname & "');"
CurrentDB.Execute sSQL, dbFailOnError
It makes it much easier to see mistakes and the sSQL string can be printed to the immediate window for debugging. You will see you have JobTtile.
It is usually better to use an instance of CurrentDB:
Dim db As DAO.Database
Set db = CurrentDB
I wonder why you do not just bind a recordset?