String builder SELECT query when a variable has an apostrophe - sql

A colleague of mine has created a program that reads a text file and assigns various values from it to variables that are used in SQL statements.
One of these variables, gsAccounts is a string variable.
Using a string builder, a SELECT statement is being built up with sql.append. At the end of the string, there is the following line:
sql.Append(" WHERE L.Account_Code IN(" & gsAccounts & ")"
The problem that I'm having is that sometimes, not always, gsAccounts (a list of account codes) may contain an account code with an apostrophe, so the query becomes
"WHERE L.Account_Code IN('test'123')"
when the account code is test'123
I have tried using double quotes to get around it in a "WHERE L.Account_Code IN("""" & gsAccounts & """")" way (using 4 and 6 " next to each other, but neither worked)
How can I get around this? The account_Code is the Primary Key in the table, so I can't just remove it as there are years worth of transactions and data connected to it.

I posted the following example here 10 years ago, almost to the day. (Oops! thought it was Jun 5 but it was Jan 5. 10.5 years then.)
Dim connection As New SqlConnection("connection string here")
Dim command As New SqlCommand
Dim query As New StringBuilder("SELECT * FROM MyTable")
Select Case Me.ListBox1.SelectedItems.Count
Case 1
'Only one item is selected so we only need one parameter.
query.Append(" WHERE MyColumn = #MyColumn")
command.Parameters.AddWithValue("#MyColumn", Me.ListBox1.SelectedItem)
Case Is > 1
'Multiple items are selected so include a parameter for each.
query.Append(" WHERE MyColumn IN (")
Dim paramName As String
For index As Integer = 0 To Me.ListBox1.SelectedItems.Count - 1 Step 1
'Name all parameters for the column with a numeric suffix.
paramName = "#MyColumn" & index
'Add a comma before all but the first value.
If index > 0 Then
query.Append(", ")
End If
'Append the placeholder to the SQL and add the parameter to the command
query.Append(paramName)
command.Parameters.AddWithValue(paramName, Me.ListBox1.SelectedItems(index))
Next index
query.Append(")")
End Select
command.CommandText = query.ToString()
command.Connection = connection

Single quotes can be "escaped" by making them double single quotes. E.g. ' becomes ''.
However this approach is generally not recommended due to the high risk of SQL injection - a very dangerous and prevalent issues. See: https://www.owasp.org/index.php/SQL_Injection
To avoid this most libraries will include some type of escaping mechanism including the use of things like prepared statements in the Java world. In the .net world this may be of use: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.prepare(v=vs.110).aspx

If you only have one with a field, this is the easiest solution
Private Function gsAccountsConvert(ByVal gsAccounts As String)
Dim gsAccountsString As String = ""
Dim StringTemp
StringTemp = gsAccounts.Split(",")
Dim i As Integer
For i = 0 To UBound(StringTemp)
StringTemp(i) = StringTemp(i).ToString.Trim
If StringTemp(i) <> "" Then
If StringTemp(i).ToString.Substring(0, 1) = "'" Then
StringTemp(i) = """" & StringTemp(i).ToString.Substring(1, Len(StringTemp(i).ToString) - 2) & """"
End If
End If
If i <> UBound(StringTemp) Then
gsAccountsString = gsAccountsString & StringTemp(i).ToString.Replace("'", "''") & ","
Else
gsAccountsString = gsAccountsString & StringTemp(i).ToString.Replace("'", "''") & ""
End If
Next
gsAccountsString = gsAccountsString.Replace("""", "'")
Return gsAccountsString
End Function

Related

Access VBA DCount data type mismatch in criteria expression when data types are obviously the same (both Text)

I'm doing a simple DCount, just looking for how many people have signed up for the same date and time. At the moment I'm just using a single date and a single time to prove the process, then I'll have it loop through all possible dates and times.
Private Sub Get_Singles()
Dim TestDate As String
Dim TestTime As String
AloneCnt = 0
Dinc = 0
Tinc = 0
TestDate = vStartDate
TestTime = "0700"
If (DCount("[ID]", VigilTable, "[fldTime] = " & TestTime) = 1) Then
' "[fldDate] = " & TestDate) & " And
AloneCnt = AloneCnt + 1
End If
End Sub
It works fine for the date (I've moved it to a different line and commented it out so I can focus on the time.).
In the table, fldDate and fldTime are both set for text (shows up as Field Size
= 255 in the properties list) and, as you can see, TestDate and TestTime are both dimmed as String.
And it works if I change the DCount line to:
(DCount("[ID]", VigilTable, "[fldTime] = '0700'")
So where's the error?
Thanks.
The error is, that you must handle date and time as data type Date. So change the data type of the fields to DateTime and:
Dim TestDate As Date
Dim TestTime As Date
Dim AloneCnt As Long
TestDate = vStartDate
TestTime = TimeSerial(7, 0, 0)
If DCount("*", "VigilTable", "[fldTime] = #" & Format(TestTime, "hh\:nn\:ss") & "# And [fldDate] = #" & Format(TestDate, "yyyy\/mm\/dd") & "#") = 1 Then
AloneCnt = AloneCnt + 1
End If
Because you hold all date/time bits as text/string, you should use the text syntax in the criteria as you showed: with quotes (notice the quotes around time string):
(DCount("[ID]", VigilTable, "[fldTime] = '" & TestTime & "'")
You could also keep Date/times in date types like #Gustav's answer.
Update:
You must be doing something wrong; here is my suggested version in VBA window, and it is not Red.
OK, I found the fix after searching several other sites; it was, as I suggested above, a problem of handling variables:
If (DCount("[ID]", VigilTable, "[fldDate]='" & TestDate & "'" & " AND [fldTime] = '" & TestTime & "'") = 1) Then
I always have trouble with those damned single quotes and can never get them in the right place (I'd tried placing single quotes several times but never got them where they are here.); I don't know if the rules are different in different places or I just don't understand the rules or both.
Thanks for all your suggestions; even things that don't work help.

MS-ACCESS VBA Multiple Search Criteria

In my GUI, I have several ways to filter a database. Due to my lack of knowledge, my VBA programming has exploded with nested IF statements. I am getting better at using ACCESS now, and would like to find a more succinct way to perform multiple filters. My form is continuous.
Is there a simple way to do the following task (I made a toy model example):
I have a combo box SITE where I can filter by work sites A, B, C. After filtering by SITE, I have three check boxes where the user can then filter by item number 1-10, 11-20, 21-30, depending on what the user selects.
Is there a way to append multiple filters (or filter filtered data)? For example, filter by SITE A, then filter A by item number 1-10?
Currently, for EACH check box, I then have an IF statement for each site. Which I then use Form.Filter = . . . And . . . and Form.FilterOn = True.
Can I utilize SQL on the property sheet to filter as opposed to using the VBA?
What I do for these types of filters is to construct a SQL statement whenever one of the filter controls is changed. All of them reference the same subroutine to save on code duplication.
What you do with this SQL statement depends on what you're trying to do. Access is pretty versatile with it; use it as a RecordSource, straight execute it, and use the results for something else, even just printing it to a label.
To try to modularize the process, here's an example of how I do it:
Dim str As String
str = "SELECT * FROM " & Me.cListBoxRowSource
Me.Field1.SetFocus
If Me.Field1.Text <> "" Then
str = AppendNextFilter(str)
str = str & " SQLField1 LIKE '*" & Me.Field1.Text & "*'"
End If
Me.Field2.SetFocus
If Me.Field2.Text <> "" Then
str = AppendNextFilter(str)
str = str & " SQLField2 LIKE '*" & Me.Field2.Text & "*'"
End If
Me.Field3.SetFocus
If Me.Field3.Text <> "" Then
str = AppendNextFilter(str)
str = str & " SQLField3 LIKE '*" & Me.Field3.Text & "*'"
End If
Me.cListBox.RowSource = str
Variables edited to protect the guilty.
My AppendNextFilter method just checks to see if WHERE exists in the SQL statement already. If it does, append AND. Otherwise, append WHERE.
Making quite a few assumptions (since you left out a lot of info in your question), you can do something like this:
Dim sSql as String
sSql = "Select * from MyTable"
Set W = Me.cboSite.Value
sSql = sSql & " WHERE MySite = " & W & ""
Set X = Me.Chk1
Set Y = Me.Chk2
Set Z = Me.Chk3
If X = True Then
sSql = sSql & " And MyItem between 1 and 10"
If Y = True Then
sSql = sSql & " And MyItem between 11 and 20"
If Z = True Then
sSql = sSql & " And MyItem between 21 and 30"
End If
DoCmd.ExecuteSQL sSql
Again, this is entirely "air code", unchecked and probably needing some edits as I haven't touched Access in some time and my VBA is likely rusty. But it should put you on the right track.
The way i use combobox filtering in access is first I design a Query that contains all the data to be filtered. The Query must contain fields to be used for filtering. QueryAllData => "SELECT Table.Site, Table.ItemNumber, FROM Table;" Then make a copy of the query and Name it QueryFilteredData and Design the report to display the data using QueryFilteredData.
Then create a form with a Site ComboBox, ItemNumber Combo Box, and Sub Report Object and Assign SourceObject the Report Name. Use Value List as the combo box Row Source type and type in the values for Row Source to get it working. To get the report to update I always unassign the SubReport.SourceOject update the QueryFilteredData and then Reassign the SubReport.SourceObject
Combobox_Site_AfterUpdate()
Combobox_ItemNumber_AfterUpdate
End Sub
Combobox_ItemNumber_AfterUpdate()
Select Case Combobox_ItemNumber.value
Case Is = "1-10"
Store_Filters 1,10
Case Is = "11-20"
Store_Filters 11,20
Case Is = "21-30"
Store_Filters 21,30
Case Else
Store_Filters 1,10
End Sub
Private Sub Store_Filters(Lowest as integer, Highest as integer)
Dim SRpt_Recset As Object
Dim Temp_Query As Variant
Dim Temp_SourceObject as Variant
Temp_SourceObject = SubReport.SourceObject
SubReport.SourceObject =""
Set SRpt_Recset = CurrentDb.QueryDefs("QueryFilteredData")
Filter_Combo_Box1 = " ((QueryAllData.[Sites])= " & Chr(39) & Combo_Box1 & Chr(39) & ") "
Filter_Combo_Box2 = (Filter_Combo_Box1 AND (QueryAllData.ItemNumber <= Highest)) OR (Filter_Combo_Box1 AND (QueryAllData.ItemNumber >= Lowest));"
Temp_Query = " SELECT " & Query_Name & ".* " & _
"FROM " & Query_Name & " " & _
"WHERE (" & Filter_Combo_Box2 & ") ORDER BY [Field_Name_For_Sorting];"
SRpt_Recset.SQL = Temp_Query
'Debug.print Temp_Query
SubReport.SourceObject = Temp_SourceObject
End Sub
After the Combo Boxes Work if the Data is going to Change like Site and Item Number then you might want to change the Row Source of the combo boxes to Use a Query that uses Select Distinct Site From QueryAllData. I don't know if Filter_Combo_Box2 step so it may need some correction. Hope this helps.

Insert number of record based on checkboxlist selected value in vb.net

I have this skill checkboxlist which contains skills that can be selected by the user. If the user select two skills,two records will be inserted to the table.
I tried this one:
Dim varSkillID As Integer()
varSkillID = split(skills, ",")
If varSkillID(0).value > 0 Then
Dim sql As String = Nothing
For I = 0 To varSkillID()
sql = "INSERT INTO tblConstituentSkills (skillID) VALUES ( " & varSkillID.Value & ")"
Next I
end if
but its not working. Thanks!
I also tried this code.
Dim varSkillID() As String = Split(skillID, ",")
For i As Integer = 0 To varSkillID.Length - 1
If varSkillID(i) <> "" Then
Using sql As New SqlProcedure("spInsertSkill")
sql.AddParameter("#ConstituentIdNo", constituentIdNo)
sql.AddParameter("#skillID", varSkillID(i))
sql.ExecuteNonQuery()
End Using
End If
Next i
It works when I only select single skill. But if I select two or more skills this error appears "Nullable object must have a value."
please use the editor help to design your request. It is very hard to read.
What does the errormessage say?
There is an End If missing
Where does constituentIdNo.Value is coming from?
To call the Sub:
Call r101("123456", "1,2,3,4")
the Sub:
Public Sub r101(ByVal constituentIdNo As String, ByVal skills As String)
Dim varSkillID() As String = Split(skills, ",")
Dim sql As String = Nothing
For i As Integer = 0 To varSkillID.Length - 1
If varSkillID(i) <> "" Then sql = "INSERT INTO tblConstituentSkills (ConstituentIdNo, skillID) VALUES (" & constituentIdNo & ", " & varSkillID(i) & ")"
Next i
End Sub
This is not the cleanest code, but the best I could create from your given feedback.
I don't see why to convert skills to integer.
I just read this and saved me.separate comma separated values and store in table in sql server
Thanks stackoverflow!you're a savior!

Connecting to Access from Excel, then create table from txt file

I am writing VBA code for an Excel workbook. I would like to be able to open a connection with an Access database, and then import a txt file (pipe delimited) and create a new table in the database from this txt file. I have searched everywhere but to no avail. I have only been able to find VBA code that will accomplish this from within Access itself, rather than from Excel. Please help! Thank you
Google "Open access database from excel VBA" and you'll find lots of resources. Here's the general idea though:
Dim db As Access.Application
Public Sub OpenDB()
Set db = New Access.Application
db.OpenCurrentDatabase "C:\My Documents\db2.mdb"
db.Application.Visible = True
End Sub
You can also use a data access technology like ODBC or ADODB. I'd look into those if you're planning more extensive functionality. Good luck!
I had to do this exact same problem. You have a large problem presented in a small question here, but here is my solution to the hardest hurdle. You first parse each line of the text file into an array:
Function ParseLineEntry(LineEntry As String) As Variant
'Take a text file string and parse it into individual elements in an array.
Dim NumFields As Integer, LastFieldStart As Integer
Dim LineFieldArray() As Variant
Dim i As Long, j As Long
'Determine how many delimitations there are. My data always had the format
'data1|data2|data3|...|dataN|, so there was always at least one field.
NumFields = 0
For I = 1 To Len(LineEntry)
If Mid(LineEntry, i, 1) = "|" Then NumFields = NumFields + 1
Next i
ReDim LineFieldArray(1 To NumFields)
'Parse out each element from the string and assign it into the appropriate array value
LastFieldStart = 1
For i = 1 to NumFields
For j = LastFieldStart To Len(LineEntry)
If Mid(LineEntry, j , 1) = "|" Then
LineFieldArray(i) = Mid(LineEntry, LastFieldStart, j - LastFieldStart)
LastFieldStart = j + 1
Exit For
End If
Next j
Next i
ParseLineEntry = LineFieldArray
End Function
You then use another routine to add the connection in (I am using ADODB). My format for entries was TableName|Field1Value|Field2Value|...|FieldNValue|:
Dim InsertDataCommand as String
'LineArray = array populated by ParseLineEntry
InsertDataCommand = "INSERT INTO " & LineArray(1) & " VALUES ("
For i = 2 To UBound(LineArray)
If i = UBound(LineArray) Then
InsertDataCommand = InsertDataCommand & "'" & LineArray(i) & "'" & ")"
Else
InsertDataCommand = InsertDataCommand & LineArray(i) & ", "
End If
Next i
Just keep in mind that you will have to build some case handling into this. For example, if you have an empty value (e.g. Val1|Val2||Val4) and it is a string, you can enter "" which will already be in the ParseLineEntry array. However, if you are entering this into a number column it will fail on you, you have to insert "Null" instead inside the string. Also, if you are adding any strings with an apostrophe, you will have to change it to a ''. In sum, I had to go through my lines character by character to find these issues, but the concept is demonstrated.
I built the table programmatically too using the same parsing function, but of this .csv format: TableName|Field1Name|Field1Type|Field1Size|...|.
Again, this is a big problem you are tackling, but I hope this answer helps you with the less straight forward parts.

ERR conversion from string to type 'double' is not valid. vb.net

I have a label name annual it display number from table in the database , this number is displayed like this 27.9828272.
I want just the 2 decimals.
I tried
If FrmLogin.CBformState.Text = "User" Then
com1.CommandText = "select * from balance where UserID = '" & FrmLogin.txtUserName.Text & "'"
com1.Connection = cn1
dr2 = com1.ExecuteReader
If dr2.Read Then
Dim b As Double
annual.Text = b
b = Math.Round(b, 2)
FirstName.Text = "'" & LCase(dr2(0)).ToString() & "'"
sick.Text = "'" & LCase(dr2(1)).ToString() & "'"
Maternety.Text = "'" & LCase(dr2(2)).ToString() & "'"
floating.Text = "'" & LCase(dr2(3)).ToString() & "'"
b = "'" & LCase(dr2(4)).ToString() & "'"
Comptime.Text = "'" & LCase(dr2(5)).ToString() & "'"
End If
any help?????????????????????
Label.Text = String.Format("{0:0}", b)
Will take the number (b) and display it in the label rounded to 0 decimal places, if that's what you mean?
Also, get into the habit of using OO principles, not procedural ones (eg insftead of LCase(Blah) do Blah.ToLower(). Then you'll be learning the .Net Framework, not VB.Net helper methods.
Finally, and most importantly, make sure you turn Option Strict on in project settings. It will force you to use the correct data types but it makes learning easier and gives you ~30% performance boost. Do not code with this setting off.
Edit: Some clarification re: String.Format...
Dim Number = 12345.6789
String.Format("{0}", Number) '12345.6789
String.Format("{0:#,##0}", Number) '12,345
String.Format("{0:0.0}", Number) '12345.7
String.Format("{0:0.00}", Number) '12345.68
String.Format("{0:000,000.00}", Number) '012,345.68
'You can also combine multiple variables...
Dim Number 2 = 10
String.Format("{0}: {1}", Number, Number2) '12345.6789: 10
Ok, editing your code...
If dr2.Read Then
Dim MyNumber = 12345.6789
annual.Text = String.Format("{0:0.00}", MyNumber) '' <-- Setting a string variable (`.Text`) with a number fails. Use the formatted string instead...
FirstName.Text = String.Format("'{0}'", dr2(0).ToLower())
sick.Text = String.Format("'{0}'", dr2(1).ToLower())
Maternety.Text = String.Format("'{0}'", dr2(2).ToLower())
floating.Text = String.Format("'{0}'", dr2(3).ToLower())
'Not sure what you're trying to do here but `b` was a Double and you're trying to set it to a string. If you just want the number do. See below.
b = "'" & LCase(dr2(4)).ToString() & "'"
Comptime.Text = "'" & LCase(dr2(5)).ToString() & "'"
End If
If you have a string containing a number ("123.456") like the one from the database, you can convert it to a double as follows:
Dim InputString = "123.456"
Dim MyNumber = Double.Parse(InputString)
If you want to format a number as a string for display, that's when you use the String.Format I mentioned above.
Incidentally, instead of using Dim without an As (which means create a variable and determine what type it is from how I use it), use specific types until you're familiar with them. Then you'll have a better mental/visual representation of what you're trying to store where...
Also, since you're putting quotes around all your variables, it would make sense to factor that out into a different method...
Public Function QuoteLower(Input as String) As String
Return String.Format("'{0}'", Input.ToLower())
End Function
Then Maternety.Text = String.Format("'{0}'", dr2(2).ToLower()) would become Maternety.Text = QuoteLower(dr2(2))
Be Warned: Quoting strings never works reliably. There are too many edge-cases and someone malicious will be able to exploit your code (What happens when someone's surname is O'Connelly or when they type SQL into your form?). Really you want to be using Parameterised Queries or an ORM (Object Relational Mapping) framework. The most common ones in .Net are the Entity Framework and nHibernate. Something to bear in mind for next time.