I'm not a very good programmer, but I think the codes are correct. Can anyone check if there are errors in it, because I always get an error at the executenonquery line.
The error is:
{"Incorrect syntax near '9'." & vbCrLf & "Unclosed quotation mark
after the character string ',#memberpic)'."}
and/or
An unhandled exception of type 'System.Data.SqlClient.SqlException'
occurred in System.Data.dll
Additional information: Incorrect syntax near '9'.
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
cn.Open()
Using cmd As New SqlClient.SqlCommand("INSERT INTO tblMembers(name, contactno, address, birthday, baptism, ministry, memberpic)VALUES('" & txtName.Text & "','" & txtContactNo.Text & "','" & txtAddress.Text & "',''" & dtpBirthday.Text & "','" & dtpBaptism.Text & "','" & txtMinistry.Text & "',#memberpic)", cn)
cmd.Parameters.Add(New SqlClient.SqlParameter("#memberpic", SqlDbType.Image)).Value = IO.File.ReadAllBytes(a.FileName)
i = cmd.ExecuteNonQuery
End Using
If (i > 0) Then
MsgBox("Save " & i & " record successfully")
Clear()
End If
cn.Close()
ShowRecord()
End Sub
One of the strings in one of the TextBox elements probably contains a single quote '.
My advice, save yourself some pain and parameterize all of the values in your SQL statement. This is good programming practice for a myriad of reasons, but it will also solve your immediate need of escaping strings that may come from a TextBox.
First you tokenize your SQL statement.
...
VALUES(#name,#contactno,#address,#birthday,#baptism,#ministry,#memberpic)
Then, you set your parameters
...
cmd.Parameters.Add(New SqlClient.SqlParameter("#name", SqlDbType.Varchar)).Value = txtName.Text
As the error says you need to close the single quotes for the string
& "',#memberpic)"
should be
& "',#memberpic) '"
^^^^
Related
I'm new to Access and have a few questions. To start off, after watching some tutorials and researching, I keep getting a Syntax error on my submission button. I am just trying to write to the database from the form. Here is my error.
Private Sub btn_Add_Click()
CurrentDb.Execute "INSERT INTO IPA_Raw_Data(Date, Auditor) " _
" VALUES(" & Me.txt_Date & ",'" & Me.txt_Name & "')"
btn_Clear_Click
End Sub
I'm sure it's something simple. Just new to this. Thanks!
Date is a reserved word in SQL, and your syntax needs a brush-up. So:
Private Sub btn_Add_Click()
CurrentDb.Execute _
"INSERT INTO IPA_Raw_Data([Date], Auditor) " & _
"VALUES (#" & Format(Me!txt_Date.Value, "yyyy\/mm\/dd") & "#,'" & Me!txt_Name.Value & "')"
End Sub
I'm pulling seven values from unbound text boxes on a form into variables. Five of the variables are string type, two are double. I'm then using sql to append the data to a table using a where statement and a global variable which contains a foreign key I used from another table, since I was unsure how to use openargs with browseto...
Option Compare Database
Private Sub Form_Load()
Dim rowN, rowR, mat, crew, perCom As String
Dim budEst, curBud As Double
End Sub
Private Sub btnCapSubmit_Click()
rowN = Me.CAP_ROW_N
rowR = Me.CAP_ROW_R
mat = Me.CAP_MAT
crew = Me.CAP_CREW
perCom = Me.CAP_PER
budEst = Me.CAP_BUD_EST
curBud = Me.CAP_BUD_CUR
Dim appendIt As String
appendIt = "INSERT INTO CAPITAL " & _
"([CAPITAL].[CAP_ROW_N], CAPITAL.[CAP_ROW_R], [CAPITAL].[CAP_MAT], [CAPITAL].[CAP_CREW], [CAPITAL].[CAP_PER], [CAPITAL].[CAP_BUD_EST], [CAPITAL].[CAP_BUD_CUR]) " & _
"VALUES ('" & rowN & "','" & rowR & "','" & mat & "','" & crew & "','" & perCom & "','" & budEst & "','" & curBud & "') WHERE [PRO_ID] = '" & gblFind & "';"
Debug.Print appendIt
DoCmd.RunSQL appendIt
DoCmd.BrowseTo acBrowseToForm, "frmSearchEdit", "NavForm.NavigationSubform", , , acFormEdit
End Sub
Access complains with error #3067, "Query input must contain at least one table or query."
I have no idea what I'm doing.
I tried using debug.print but didn't see anything right off the bat. Then again I've been working on this database all day, so I could be overlooking something really easy.
P.S. I also tried replacing the variables with Me.CAP_ROW_N (textbox names), but no dice.
It's unclear what you are trying to do here, but an INSERT INTO ... VALUES () statement does not take a WHERE clause. Error 3067 is "Query input must contain at least one table or query." You are likely seeing this error because you have included a WHERE clause but you are not selecting existing values from a table.
Try this instead:
appendIt = "INSERT INTO CAPITAL " & _
"([CAPITAL].[CAP_ROW_N], CAPITAL.[CAP_ROW_R], [CAPITAL].[CAP_MAT], [CAPITAL].[CAP_CREW], [CAPITAL].[CAP_PER], [CAPITAL].[CAP_BUD_EST], [CAPITAL].[CAP_BUD_CUR]) " & _
"VALUES ('" & rowN & "','" & rowR & "','" & mat & "','" & crew & "','" & perCom & "','" & budEst & "','" & curBud & "');"
There are several other issues here as well. I will just list them and let you Google for more guidance:
You should use the .Execute DAO method instead of DoCmd.RunSQL because it allows for better error handling, especially when used with the dbFailOnError option.
You will eventually run into trouble using single-quotes on unescaped inputs. For example, WHERE LastName = 'O'Malley'
You appear to be treating all seven values as text by wrapping them in quotes, even though you said two of your values were numeric (double). Numeric values do not get quotes.
Do not qualify the field names with the table name in your field list.
A WHERE clause doesn't belong in an INSERT ... VALUES statement; get rid of that.
This is a smaller-scale example of the pattern I think you want:
appendIt = "INSERT INTO CAPITAL " & _
"([CAP_ROW_N], [CAP_ROW_R]) " & _
"VALUES ('" & rowN & "','" & rowR & "');"
However, I suggest you tackle this with a parameter query.
appendIt = "INSERT INTO CAPITAL " & _
"(CAP_ROW_N, CAP_ROW_R) " & _
"VALUES (pCAP_ROW_N, pCAP_ROW_R);"
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, appendIt)
qdf.Parameters("pCAP_ROW_N") = Me.CAP_ROW_N.Value
qdf.Parameters("pCAP_ROW_R") = Me.CAP_ROW_R.Value
qdf.Execute dbFailOnError
Note I used the text box values for the parameter values directly --- instead of declaring variables to hold the text box values.
Also notice one of the benefits of parameter queries is you needn't bother with delimiters for the values: quotes for text; or # for dates.
I have this simple code of vba access to update product in the database. But when I debug, it stops at the DoCmd statement and got run-time error. I've made research about this kind of error and code, and had changed the code but still caused an error. Below is my simple code to update the product value.
Sub UpdateProduct()
Dim mySql As String
mySql = "UPDATE " & Forms!UPDATE_PRODUCT!cbxLensType _
& " SET LOT_NO = " & Forms!UPDATE_PRODUCT!txtLotNo _
& " WHERE EAN_CODE = " & Forms!UPDATE_PRODUCT!txtEan & ";"
DoCmd.RunSQL mySql
End Sub
Could you help me to explain what is the problem to my code? Is it because of the update syntax?
Thanks in advance.
**New to access vba
Since EAN_CODE is Text type you need to enclose it inside single quotes.
Sub UpdateProduct()
Dim mySql As String
mySql = "UPDATE [" & Forms!UPDATE_PRODUCT!cbxLensType _
& "] SET LOT_NO = " & Forms!UPDATE_PRODUCT!txtLotNo _
& " WHERE EAN_CODE = '" & Forms!UPDATE_PRODUCT!txtEan & "';"
DoCmd.RunSQL mySql
End Sub
If LOT_NO is also a Text type, make sure that it is also enclosed in Single quotes.
Dim conntps As MySqlConnection
Dim myconnstringtps As String
conntps = New MySqlConnection()
Dim mycommand As New MySqlCommand
Dim Updatepayments As String = "update payments set payments.payorname='" & _
epayorname.Text & "', payments.cardnumber='" & eccnumber.Text & _
"', payments.bankname='" & ebankname.Text & "', payments.checkaccountnumber='" & _
eaccountnumber.Text & "', payments.checkroutingnumber='" & _
erouting.Text & "', payments.cardexpirationdate='" & eexpmonth.Text & "/" & _
eexpireyear.Text & "', payments.cardexpirationmonth='" & _
eexpmonth.Text & "', payments.cardexpirationyear='" & eexpireyear.Text & _
"', payments.cardaddress='" & eaddy.Text & "', payments.cardzipcode='" & _
ezip.Text & "', payments.threedigitnumber='" & ecvv.Text & _
"' where payments.filenumber='" & TextBox1.Text & "' and paymentstatus='PENDING';"
myconnstringtps = "server=localhost; user id=root; " & _
"password=1C0cac0la; database=collectionsmax"
Try
conntps.Open()
Try
mycommand.Connection = conntps
mycommand.CommandText = Updatepayments
mycommand.ExecuteNonQuery()
conntps.Close()
mycommand.Dispose()
Catch myerror As MySqlException
MsgBox("error connecting:" & myerror.Message)
End Try
Catch myerror As MySqlException
MsgBox("error connecting:" & myerror.Message)
Finally
If conntps.State <> ConnectionState.Closed Then conntps.Close()
MsgBox("Successfully Changed")
End Try
I am not getting any errors or exceptions when attempting to run the code.
I have tried to output the generated update query to a text box and running the code though mysql management studio, and it works perfectly. so im pretty sure its not an issue with the actual query being sent to the server.
I have used almost this exact same code to do insert into statements with no issues.
It is not updating the database when the code is ran through my VB.net application using the above outlined code.
You don't set the connection string in the MySqlConnection
myconnstringtps = "server=localhost; user id=root; password=1C0cac0la;......"
conntps = New MySqlConnection(myconnstringtps)
apart from that, you need to use parametrized query to avoid problems with single quotes inside your strings and the Sql Injection Attack security problem
Dim Updatepayments As String = "update payments " & _
"set payments.payorname=#name," & _
"payments.cardnumber=#cnum," & _
"payments.bankname=#bank," & _
"payments.checkaccountnumber=#actnum," & _
"payments.checkroutingnumber=#routing," & _
"payments.cardexpirationdate=#monthyear," & _
"payments.cardexpirationmonth=#month," & _
"payments.cardexpirationyear=#year," & _
"payments.cardaddress=#address," & _
"payments.cardzipcode=#zip," & _
"payments.threedigitnumber=#digits " & _
"where payments.filenumber=#file and paymentstatus='PENDING'"
Dim mycommand As New MySqlCommand(Updatepayments, conntps)
mycommand.Parameters.AddWithValue("#name", epayorname.Text)
mycommand.Parameters.AddWithValue("#cnum", eccnumber.Text)
mycommand.Parameters.AddWithValue("#bank", ebankname.Text)
mycommand.Parameters.AddWithValue("#actnum", eaccountnumber.Text);
mycommand.Parameters.AddWithValue("#routing", erouting.Text)
mycommand.Parameters.AddWithValue("#monthyear", eexpmonth.Text & "/" & eexpireyear.Text)
mycommand.Parameters.AddWithValue("#month", eexpmonth.Text)
mycommand.Parameters.AddWithValue("#year", eexpireyear.Text)
mycommand.Parameters.AddWithValue("#address", eaddy.Text)
mycommand.Parameters.AddWithValue("#zip", ezip.Text)
mycommand.Parameters.AddWithValue("#digits", ecvv.Text)
mycommand.Parameters.AddWithValue("#file", TextBox1.Text)
Other problematic point: Are you sure that your fields are all of string type? You pass for every field a string and surround the value with single quotes. This could fail if someone of your fields are not of string type. (these fields in particular could be not of string type payments.cardnumber, payments.checkaccountnumber, payments.cardexpirationmonth,payments.cardexpirationyear,payments.threedigitnumber)
Use command parameters. This makes it both safer (SQL injection) and easier to handle.
Dim Updatepayments As String = "UPDATE payments SET payments.payorname=#1, " & _
"payments.cardnumber=#2, ..." & _
"WHERE payments.filenumber=#11 AND paymentstatus='PENDING';"
mycommand.Parameters.AddWithValue("#1", epayorname.Text);
mycommand.Parameters.AddWithValue("#2", eccnumber.Text);
...
You can also use parameter names like #epayorname with SQL-Server but some connection types (like ODBC) only allow positional parameters.
Red alert You are obviously dealing with credit card information here and yet you are leaving yourself and your customers vulnerable to SQL injection attacks!
Also you have a password in your code that you posted on the public Internet!
(And Steve seems to have the right answer.)
I am new to VB programming and have come across an problem:( after a couple of days trying to resolve this need some help!
I am trying to pass some information from a VB form to my MySQL database. i have named all the textbox's the same as the field in the database and checked all my database fields and textbox names which are all correct.
When i try to enter information into a form I sometimes get an error at the .executeNonQuery section of the code.
To test, I outputted the SQLStatement string to a textbox ( which pulled through all the fields from the textboxes correctly) then manually inputted the completed SQL query into the database and it worked. But when I try to do this in one go it seems to fail if there is too much text ( if i enter 'a' into each field it works). Are they limits to the size of the SQL query that can be passed from VB?? all the MySql database fields are set to text with no size limits.
Thanks in advance!!!
Public Sub SaveQuote(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
SQLConnection.Close()
MsgBox("successfully Added!")
SQLConnection.Dispose()
End Sub
Private Sub CmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdSave.Click
Dim SQLstatement As String = "INSERT INTO laptopstock(forename,surname,emailaddress,contactnumber,quotedate,manufacturer,model,os,battery,drive,defects) VALUES('" & forename.Text & "','" & surname.Text & "','" & emailaddress.Text & "','" & contactnumber.Text & "', CURDATE(),'" & manufacturer.Text & "','" & modelnumber.Text & "','" & os.Text & "','" & batterycondition.Text & "','" & drivetype.Text & "','" & defects.Text & "')"
SaveQuote(SQLstatement)
End Sub
'Test SQL query
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim testSQLstatement As String = "INSERT INTO laptopstock(forename,surname,emailaddress,contactnumber,quotedate,manufacturer,model,os,battery,drive,defects) VALUES('" & forename.Text & "','" & surname.Text & "','" & emailaddress.Text & "','" & contactnumber.Text & "', CURDATE(),'" & manufacturer.Text & "','" & modelnumber.Text & "','" & os.Text & "','" & batterycondition.Text & "','" & drivetype.Text & "','" & defects.Text & "')"
testbox.Text = testSQLstatement
End Sub
here is the output from testSQLstatement = testbox.text
INSERT INTO laptopstock(forename,surname,emailaddress,contactnumber,quotedate,manufacturer,model,os,battery,drive,defects) VALUES('Joe','Bloggs','J.bloggs#jbloggs.com','07777777777', CURDATE(),'Sony','Vaio','Windows 7 Pro','Poor','DVD-Rom','Faulty Screen')
from what i can see it is correctly formatted and when i enter this directly into a query on the MySql server a record is created
Does your application SQL login have insert rights on this table? Try executing a grant statment in SQL console directly:
"grant insert on dbo.laptopstock to (add you application login here)"
Also, I why are you passing the SQLStatement byref? You are not modifying it, so use byval. This shouldn't impact the code, but is a good practice.
I see you state that sometimes you get an error, so we can asume it is working code. That leads me to believe it is in your input data. Do the fields accept nulls? Are they the right format? Also, one of these things is not like the others, the date. You are passing the curdate() function in the insert. If the fields are all strings like you mention, then you are performing an implicit conversion from date to string. You could as easily built the insert string using the Vb.Net equivalent. (Date.Now.ToString).
Lastly, it is hard to debug this without more detailed information about the
error. As you have not posted code for your SQLConnection and MySLCommand objects (sure you don't mean MySQLCommand as New SQLCommand) I have to assume they work.