Ignore apostrophe in sql query from text box - sql

I'm thoroughly enjoying my stay here at stack overflow, I have found more useful information than I can count.
However, through all of my searches, I have yet to find an answer to my issue.
I have a Winforms app that inputs data into an SQL database. I have an issue with the text box in this form posting to the database.
If a user inputs an apostrophe or a quotation mark the query in Visual studio stops at where that apostrophe is in the text box even if there is more data after that and does not enter the data into the database.
I know that putting a second apostrophe will cancel out the one that was input, however, I can't seem to read the data in the text box before the query executes to cancel them out. I have put an example of what works in this text box and what breaks the query in this question for further clarification.
I apologize, everyone, it seems I forgot to put my code into this post.
Dim InsertQuery As String = "INSERT INTO SelfInstallNotes (Troubleshooting, DateAndTime, [CL to OD], [Swapped Dscntd Clocks], [Upgrading to SaaS], [Update Version], [Created RPF], [Created RMA], [Clock Serial], [Case Number], [User], [Grabbed], [Account Manager], [Transferred to AM]) VALUES('" & Hidden.TextBox6.Text.ToString & "'" & "," & "'" & DateTimePicker1.Value & "'" & "," & "'" & CheckBox1.CheckState & "'" & "," & "'" & CheckBox2.CheckState & "'" & "," & "'" & CheckBox3.CheckState & "'" & "," & "'" & CheckBox4.CheckState & "'" & "," & "'" & CheckBox5.CheckState & "'" & "," & "'" & CheckBox6.CheckState & "'" & "," & "'" & TextBox2.Text & "'" & "," & "'" & TextBox1.Text & "'" & "," & "'" & TextBox6.Text & "'" & "," & "'" & Hidden.TextBox3.Text & "'" & "," & "'" & Hidden.TextBox4.Text & "'" & "," & "'" & Hidden.TextBox5.Text & "'" & ")"
But after reading all of you answers this code is most certainly WRONG and can cause issues later on down the road. I will try the answer posted below and update the thread accordingly.
This query will not post to DB due to the apostrophe in can't
while this input in the textbox will post without any issues, as there is no apostrophe or quotation marks.

The problem is worse than you know. This is also a huge security issue. Try putting the following text in your input:
'; DROP TABLE [MyCallTable];--
Or don't, if you value your data.
Fortunately, the solution is the same for both the security issue and for normal, everyday apostrophes; you quarantine all user input from the rest of the SQL command by using query parameters.
Here's an example:
var SQL = "SELECT * FROM Users WHERE LastName = #LastName";
using (var cn = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(SQL, cn))
{
//TextBox1 can have text with ' characters, and it won't matter.
cmd.Parameters.Add("#LastName", SqlDbType.NVarChar, 25).Value = TextBox1.Text;
cn.Open();
DataGrid1.DataSource = cmd.ExecuteReader();
}
There are other forms of this, too, depending on your environment, but the important thing is the text input is never at any time substituted directly in the SQL command — not even on the database server. This prevents any possibility of bad input injecting into the SQL. It also makes it easier to get things like date formats right, as now the ADO.Net provider will handle conversions for you.
The main thing to understand is if you ever find yourself doing anything like this:
sql = "SELECT * FROM [Table] WHERE Field='" + TextBox.Text + "'";
or even this:
sql = "SELECT * FROM [Table] WHERE Field='" + TextBox.Text.Replace("'", "''") + "'";
you're doing something very wrong.
This is one of those things that's important enough it's worth going back through an old code base to fix every instance where you've done it the wrong way before the next release, and it's not often I'll say that.

var stringvariable = tempString.Replace("'", "''");// this escapes the single quote

Related

Access Form Dlookup - Using a Combo box for the expression value

Good Morning,
I am doing some work for a colleague and he wants a form creating where he can change to column that is looked at through a combo box as well as the criteria
I have tried the following
=DLookUp(" & [Combo8] & ","Product Guidelines","PC = '" & [Combo2] & "'")
but get an error, if i hard code the expression to one of the columns it works fine but when it's set to look at the combo box it doesn't work, I have tried several variants of the code but have no ran out of ideas
Please can someone help
Thank you
Look closely at your code. You are passing the literal string " & [Combo8] & " (including spaces and ampersands) as first parameter to DLookup.
Try
=DLookUp([Combo8], "Product Guidelines", "PC = '" & [Combo2] & "'")
or if the content of Combo8 has spaces,
=DLookUp("[" & [Combo8] & "]", "Product Guidelines", "PC = '" & [Combo2] & "'")
or maybe even with quotes around it:
=DLookUp("""[" & [Combo8] & "]""", "Product Guidelines", "PC = '" & [Combo2] & "'")
The syntax would be:
=DLookUp("[FieldNameToLookUp]","[Product Guidelines]","PC = '" & Me![Combo2] & "'")
as you probably don't have a field named Combo8.
If Combo8 holds that name, it would be:
=DLookUp("[" & Me!Combo8 & "]","[Product Guidelines]","PC = '" & Me![Combo2] & "'")

Issue with SQL code in Microsoft Access

I have a button in my database that is supposed to find a record when it is clicked. The issue I am encountering is that I want it to search for a record based on two fields.
This is my code:
I am using the SearchForRecord macro with Where Condition
="[Short Title] = " & "'" & [Combo101] & "'" And "[Baseline] = " & "'" & [Combo103] & "'"
It is not liking this. If I just have the Where condition as
="[Short Title] = " & "'" & [Combo101] & "'"
or I have it as
="[Baseline] = " & "'" & [Combo103] & "'"
then it works fine. But when I try to combine the two (which I need to do) it will not find any records.
I tried to break it up into two separate SearchForRecord macros and while that did return records when I clicked the button, it still wasn't working properly.
It would be ideal if someone could let me know why my original code was not working and what needs to be done to fix it.
Try:
="[Short Title] = '" & [Combo101] & "' AND [Baseline] = '" & [Combo103] & "'"

Syntax Error OledbException delete statement

I can't fugure out what my syntax error is here. Anyone spot it? Or am I going about this all wrong?
Dim myCommand As New OleDb.OleDbCommand("delete * from Team where intPlayerNo='" & txtUniformNo.Text & "'_ strFirstName='" & txtFirstName.Text & "'_ strLastName='" & txtLastName.Text & "'_ strParentName='" & txtParent.Text & "'_ strAddress='" & txtAddress.Text & "'_ strCity='" & txtCity.Text & "'_ strState='" & txtState.Text & "'_ strZipCode='" & txtZip.Text & "'_ strPhone='" & txtPhone.Text & "'_ intAge='" & txtAge.Text & "'", myConnection)
A delete statement is Delete From Team Where...
You would be best advised to use Parameterized Queries to avoid SQL Injection Attacks
Your syntax is wrong because you have multiple WHERE conditions but you don't use the correct AND/OR to connect the conditions together. Of course the DELETE * FROM table syntax is accepted only by MS-ACCESS, but the correct SQL syntax is DELETE FROM (without the *) and is accepted also by Access so it is better to use the standard.
Said that you need to use a parameterized query in your command and not a string concatenation
Dim cmdText = "DELETE FROM Team " & _
"WHERE intPlayerNo = #playerNo AND " & _
"strFirstName = #firstName AND " & _
".... and so on with the other fields "
Dim myCommand As New OleDb.OleDbCommand(cmdText, myConnection)
myCommand.Parameters.Add("#playerNo", OleDbType.VarWChar).Value = txtUniformNo.Text
myCommand.Parameters.Add("#firstName", OleDbType.VarWChar).Value = txtFirstName.Text
... continue with the other parameters required by the WHERE statement
myCommand.ExecuteNonQuery()
Using parameters will keep your code safe from Sql Injection and avoid syntax errors if some of your textbox values contains a single quote.
Keep in mind that if your table has a primary key, then your WHERE could simply reduced to only the PrimaryKeyFieldName = #Value

Trouble using variables in VBA SQL WHERE Clause

I am trying to update a table using variables in VBA for Access. The statement is below.
DB.Execute "UPDATE tblSearchersList SET '" & vSearcherDay & "' = " & VHours & "
WHERE Member= '" & Me.cboMember.Column(1) & "'AND [Mission] = '" & Me.Mission & "'"
tblSearcherList is table to update
vSearcherDay is a variable that combines the letter "d" with a number, et(1,2,3,4,5) depending on other query
VHours is a decimal number (number of hours)
Member is a text value from Form Field Me.cboMember.Column(1)
Mission is a text value from form field Me.Mission
I get Runtime error 3061 - Too few parameters expected 2.
Hope I can get some help with this as I have been fighting it for awhile and am losing the battle.
Thanks
New code is this:
Sorry bout the comments thing. I am new and didn't quite know how to do this.
DB.Execute "UPDATE tblSearchersList SET " & vSearcherDay &_
" = " & VHours & " WHERE Member= '" & Me.cboMember.Column(1) & "' &_
" And [Mission] = '" & Me.Mission & "'"
I am quite embarrassed about this but I had the Member field name wrong. Should've been
MemberName instead. I really do appreciate all the quick help I got and will do better next time. It works perfectly. Thank you all.
Don't use apostrophes around field name. Instead
SET '" & vSearcherDay & "' = " &
do
SET " & vSearcherDay & " = " &

extract fields from a huge csv file and write them to a table, text or csv file

i have this huge csv file, it's 4GB, don't know how many rows but 320 columns.
since it can't be open in any program (except using 3rd party programs to split the file into multiple pieces) i'm trying to fins a way to extract the data i need. i only need about 10-15 columns from it.
i saw many solutions on the net (most in vbs) but i couldn't get any of them to work. i'd get errors and i don't know vbs to be able to troubleshoot them.
can anyone help please?
thank you
PS here's one example of the vbs code i found and tried using that i had no luck with.
the original error was "800a01f4 variable is undefined", on the net it was suggested to take out OPTION EXPLICIT. once i do that the next error is "800a01fa class not defined".
in both cases the line giving the error is "Set adoJetCommand = New ADODB.Command"
Option Explicit
Dim adoCSVConnection, adoCSVRecordSet, strPathToTextfile
Dim strCSVFile, adoJetConnection,adoJetCommand, strDBPath
Const adCmdText = &H0001
' Specify path to CSV file.
strPathToTextFile = "C:\Users\natalie.rynda\Documents\Temp\RemailMatch\"
' Specify CSV file name.
strCSVFile = "NPIOld.csv"
' Specify Access database file.
strDBPath = "C:\Users\natalie.rynda\Documents\Temp\RemailMatch\NPIs.mdb"
' Open connection to the CSV file.
Set adoCSVConnection = CreateObject("ADODB.Connection")
Set adoCSVRecordSet = CreateObject("ADODB.Recordset")
' Open CSV file with header line.
adoCSVConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & strPathtoTextFile & ";" & _
"Extended Properties=""text;HDR=YES;FMT=Delimited"""
adoCSVRecordset.Open "SELECT * FROM " & strCSVFile, adoCSVConnection
' Open connection to MS Access database.
Set adoJetConnection = CreateObject("ADODB.Connection")
adoJetConnection.ConnectionString = "DRIVER=Microsoft Access Driver (*.mdb);" _
& "FIL=MS Access;DriverId=25;DBQ=" & strDBPath & ";"
adoJetConnection.Open
' ADO command object to insert rows into Access database.
Set adoJetCommand = New ADODB.Command
Set adoJetCommand.ActiveConnection = adoJetConnection
adoJetCommand.CommandType = adCmdText
' Read the CSV file.
Do Until adoCSVRecordset.EOF
' Insert a row into the Access database.
adoJetCommand.CommandText = "INSERT INTO NPIs " _
& "(NPI, EntityTypeCode, ReplacementNPI, EIN, MAddress1, MAddress2, MCity, MState, MZIP, SAddress1, SAddress2, SCity, SState, SZIP, ProviderEnumerationDate, LastUpdateDate, NPIDeactivationReasonCode, NPIDeactivationDate, NPIReactivationDate) " _
& "VALUES (" _
& "'" & adoCSVRecordset.Fields("NPI").Value & "', " _
& "'" & adoCSVRecordset.Fields("Entity Type Code").Value & "', " _
& "'" & adoCSVRecordset.Fields("Replacement NPI").Value & "', " _
& "'" & adoCSVRecordset.Fields("Employer Identification Number (EIN)").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider First Line Business Mailing Address").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider Second Line Business Mailing Address").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider Business Mailing Address City Name").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider Business Mailing Address State Name").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider Business Mailing Address Postal Code").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider First Line Business Practice Location Address").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider Second Line Business Practice Location Address").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider Business Practice Location Address City Name").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider Business Practice Location Address State Name").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider Business Practice Location Address Postal Code").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider Enumeration Date").Value & "', " _
& "'" & adoCSVRecordset.Fields("Last Update Date").Value & "', " _
& "'" & adoCSVRecordset.Fields("NPI Deactivation Reason Code").Value & "', " _
& "'" & adoCSVRecordset.Fields("NPI Deactivation Date").Value & "', " _
& "'" & adoCSVRecordset.Fields("NPI Reactivation Date").Value & "')"
adoJetCommand.Execute
adoCSVRecordset.MoveNext
Loop
' Clean up.
adoCSVRecordset.Close
adoCSVConnection.Close
adoJetConnection.Close
If your CSV file is straightforward, without newlines or commas in unexpected places, then the standard *nix tool awk would be useful. It would allow you to easily extract the 15 columns you are looking for to a new CSV file. This blog post gives an explanation how to use it on CSV files.
Suppose that you want to extract columns 1, 3 and 7 from file.csv, then you could do this with the command
awk -F, '{print $1","$3","$7;}' file.csv
Your Windows machine probably does not have awk installed. There are a few options:
You can find it in
MSYS, which basically
provides you with a Unix-like shell environment in Windows. To me, this seems to be the easies way to go.
Another option seems to be Gawk for
Windows, but I
have no experience with that, so no guarantees.
You could try to achieve the same result using the Windows
PowerShell, as explained in this blog
post
-- if you have that available. Again, I have no experience trying that.
Last but not least, you could switch to Linux, for example in a
virtual machine. awk is usually available in *nix environments.
If you are parsing a more awkward CSV file, then check out parse csv file using gawk for a bunch of suggestions.
In the VBE editor
Then find in the List the Microsoft Activex Data Objects Library.
Not sure which version might be appropriate, but probably 6
It seems like your code doesn't know what the ADODB.COMMAND is and this should resolve that.
I only know I was able to copy your code, and was able to step through it successfully, when the reference was set.
Hope this helps explain