Trouble building an SQL Query from VB.NET checklistbox options - sql

I am trying to create an sql query from options selected in a checkListBox. The user will select all of the modules they want (in the checklistbox) to include data from, it will then build the query to collect this data. They will also enter a range for a rating value that will be included in the query. I am very new to using sql so I am struggling to understand what operator is missing from the final query.
This is what I have at the moment:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim h As Integer
Dim queryString As String
Dim moduleArray(6) As String
Dim counter As Integer = 0
Dim provider As String
Dim database As String
Dim connString As String
Dim moduleLen As Integer = 0
Dim moduleString As String = ""
Dim sqlquery As New OleDb.OleDbCommand
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Change the following to your access database location
database = "C:\Users\mello_000\OneDrive\Google Drive\Computing\Exampapergenerator\users.accdb"
connString = provider & database
Dim myConnection As OleDbConnection = New OleDbConnection(connString)
myConnection.Open()
sqlquery.Connection = myConnection
For h = 0 To h = 6
For Each item As String In Me.CheckedListBox1.CheckedItems
moduleArray(moduleLen) = item
If moduleArray(moduleLen) = "" Then
Else
moduleLen = moduleLen + 1
End If
Next
Next
For i = 0 To moduleLen
If i = 0 Then
moduleString = "'" & moduleArray(i) & "'"
ElseIf i > 0 Then
moduleString = moduleString & "'OR'" + "'" & moduleArray(i) & "'"
End If
Next
queryString = ("SELECT QText FROM Question WHERE QModule = '" & moduleString & "' AND QRating BETWEEN '" & TextBox1.Text() & "'AND'" & TextBox2.Text())
sqlquery.CommandText = queryString
sqlquery.ExecuteNonQuery()
End Sub
However I am getting the output to be: "SELECT QText FROM Question WHERE QModule = ''C1''OR''C2'' AND QRating BETWEEN '1'AND'2"
and an error:
Syntax error (missing operator) in query expression 'QModule = ''C1''OR''C2'' AND QRating BETWEEN '1'AND'2'.
Also, what would be the best way of outputting all of the returned data in a numbered list, in a form that would be printable?

Why are you doing this For h = 0 To h = 6 instead of just For h = 0 To 6?
You don't need single quotes around "'OR'" just use " OR ".
And your SQL syntax is wrong. This QModule = ''C1''OR''C2'' either needs to be QModule = 'C1' OR QModule = 'C2' or a better way QModule IN ('C1','C2')
Assuming QRating is numeric, you don't need single quotes. This QRating BETWEEN '1'AND'2' should be QRating BETWEEN 1 AND 2.
Also you should look into using SQL parameters so you don't have to worry about quotes or escaping them if you have quotes in your data.

Related

vb.net trim word from end of string

I am trying to run an SQL query in my vb.net application using a loop
SQL = "SELECT * FROM table WHERE "
For m = 1 To num_array
SQL = SQL & "type = '" & array(m, 1) & "' OR "
Next
but its showing an OR at the end.
how can i trim this last OR from my query?
This seems a job for a StringBuilder
Dim sql = new StringBuilder("SELECT * FROM table WHERE ")
For m = 1 To num_array
sql.Append("type = '" & array(m, 1) & "' OR ")
Next
If num_array > 0 Then
sql.Length -= 4
End If
However you should pay special care to your string concatenation. It seems that your array doesn't contain numbers but string because you are putting everything between single quotes and this means that your type field is a string not a number.
Of course I hope that your array content is not directly inserted by your user otherwise you have a big security risk called Sql Injection. Anyway look at how to build a parameterized query.
Something like this
Dim prms = New List(Of SqlParameter)()
Dim num_Array = 4
Dim sql = New StringBuilder("SELECT * FROM table WHERE ")
For m = 1 To num_array
sql.Append("type = #p" & m & " OR ")
prms.Add(New SqlParameter("#p" & m, array(m, 1)))
Next
If num_array > 0 Then
sql.Length -= 4
End If
Dim cmd = new SqlCommand(sql.ToString(), connection)
cmd.Parameters.AddRange(prms.ToArray())

VB NET - Select * From issue

I have some wierd exception.
I have Access database with 2 tables, one named MYSB_DB and the other Employee.
I'm using the code below when I want to filter on something like that:
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String = String.Empty '
Dim pName As String = String.Empty
Dim fName As String = String.Empty
Dim ColpName As String = String.Empty
Dim ColfName As String = String.Empty
Dim ch As Integer = InStr(1, cmbEmployees.Text, " ", CompareMethod.Text)
pName = cmbEmployees.Text.Substring(0, ch)
fName = cmbEmployees.Text.Substring(ch, cmbEmployees.Text.Length - ch)
ColpName = "שדה1"
ColfName = "שדה2"
sql = "SELECT * FROM Employee WHERE [" & ColpName & "]=" & pName & ";"
da = New OleDb.OleDbDataAdapter(sql, Me.EmployeeTableAdapter.Connection.ConnectionString)
da.Fill(ds, Me.MYSB_DataBaseDataSet1.Employee.TableName)
I only change between the tables name in the code.
When I'm using this code for MYSB_DB table, the code is running well, but when I'm using the code for Employee table, I have an exception.
Any ideas why it's happening?
pName is a string, so it must be quoted:
sql = "SELECT * FROM Employee WHERE [" & ColpName & "]='" & pName & "';"

Data type mismatch in criteria expression when querying database

I'm a student currently doing my programming coursework. I am trying to get the MemberID from the Access database using a button in my DataGridView, but I end up with an error Data type mismatch in criteria expression when I select the member I wish to view. This is my code below:
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim Member As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
da = New OleDb.OleDbDataAdapter(Query, Conn)
Connect = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = \\DRS-SR-002\RMShared Documents\Computer Programming\Programs\year13\Kevin\Project\Database tables\DBTables.accdb"
Conn = New OleDb.OleDbConnection(Connect)
If e.ColumnIndex <> 4 Then
Exit Sub
End If
Dim MemberSelectedID As String = DataGridView1.Rows(e.RowIndex).Cells(0).Value
GroupBox1.Show()
Query = "SELECT MemberID FROM tblMember WHERE [MemberID] = """ & MemberSelectedID & """"
Conn.Open()
da = New OleDb.OleDbDataAdapter(Query, Conn)
da.Fill(ds, "Selected Member")
Conn.Close()
Member = ds.Tables("Selected Member").Rows(0).Item(0)
TextBox1.Text = Query
End Sub
Your Query is wrong.
It should be like this.
Query = "SELECT MemberID FROM tblMember WHERE [MemberID] = " & MemberSelectedID
OR
Query = "SELECT MemberID FROM tblMember WHERE [MemberID] = '" & MemberSelectedID & "'"
MemberID field is Integer so no need to specify it as string.
In SQL Server single quote ' is used to specify string not double quote ".
You are getting the MemberSelectedID from the DataGridView as String and then using it to query the database, on which I assume that it is defined as Numeric. That's the reason of the data type mismatch error
Try:
Dim MemberSelectedID As Integer = DataGridView1.Rows(e.RowIndex).Cells(0).Value
And
Query = "SELECT MemberID FROM tblMember WHERE MemberID = " & MemberSelectedID

ORA-01704: string literal too long when updating a record

I am trying to update an Oracle Database record and i keep getting this error:
ORA-01704: string literal too long 5
I looked up that error and it seems that i have a limit of 4000 charters since i am using Oracle 10g. However, the prgblem is that its the same exact data i am putting back into that record so that is why i am unsure as to why its giving me that error for the same amount of data i took out of it.
Here is my update code:
Dim myCommand As New OracleCommand()
Dim ra As Integer
Try
myCommand = New OracleCommand("Update CSR.CSR_EAI_SOURCE Set STATUS_CODE = 'Blah', COMPLETE_DATE = '', DATA = '" & theData & "' WHERE EID = '81062144'", OracleConnection)
ra = myCommand.ExecuteNonQuery()
OracleConnection.Close()
Catch
MsgBox("ERROR" & Err.Description & " " & Err.Number)
End Try
I'm not sure if there is anything special you have to do in order to update a clob or not.
I extract the clob like so:
Dim blob As OracleClob = dr.GetOracleClob(9)
Dim theData As String = ""
theData = blob.Value
And it works just fine extracting but just not putting it back in.
Any help would be great!
David
UPDATE CODE
Dim OracleCommand As New OracleCommand()
Dim myCommand As New OracleCommand()
Dim ra As Integer
While dr.Read()
Dim blob As OracleClob = dr.GetOracleClob(9)
Dim theData As String = ""
theData = blob.Value
theData = Replace(theData, "…", " ")
Try
Dim strSQL As String
isConnected2 = connectToOracleDB2()
OracleConnection.Close()
If isConnected2 = False Then
MsgBox("ERRORConn: " & Err.Description & " " & Err.Number)
Else
myCommand.Connection = OracleConnection2
strSQL = "Update CSR.CSR_EAI_SOURCE Set STATUS_CODE = 'ERROR', COMPLETE_DATE = '', DATA = :1 WHERE EID = '" & theEID & "'"
myCommand.CommandText = strSQL
Dim param As OracleParameter = myCommand.Parameters.Add("", OracleDbType.Clob)
param.Direction = ParameterDirection.Input
param.Value = theData
Application.DoEvents()
ra = myCommand.ExecuteNonQuery()
Application.DoEvents()
OracleConnection2.Close()
Application.DoEvents()
End If
Catch
MsgBox("ERROR: " & Err.Description & " " & Err.Number)
OracleConnection2.Close()
End Try
End While
dr.Close()
OracleConnection.Close()
Do not hardcode the value into your SQL query. Instead wrap it in a parameter. Like this:
Dim strSQL As String
strSQL = "Update CSR.CSR_EAI_SOURCE Set STATUS_CODE = 'Blah', COMPLETE_DATE = '', DATA = :1 WHERE EID = '81062144'"
myCommand.CommandText=strSQL
And then:
Dim param As OracleParameter=myCommand.Parameters.Add("",OracleDbType.Clob)
param.Direction=ParameterDirection.Input
param.Value=blob.Value
You can (and should) of course add all other variables (status code, complete date, eid) of your query as parameters, too, instead of hard-coding them into your SQL.
Varchar2 in sql has a limitations of 4000 characters. This limitation does not apply to the data stored in a varchar column. You need to convert this to pl\sql or specify some other column type. ( I am not a php expert. So I cannot provide any sample, just the reason for your error).
Essentially you need to specify the data type as clob while executing the bind query. Otherwise it will default to varchar2 and the above limitation will apply.

problem in inserting list box value in visual basic 2008

i have a problem in inserting the listbox value into mysql database in vb 2008 i.e
if i select a video file i.e D:\videos\video1.mpg and add a msgbox() event before inserting into data base it shows the exact path i.e D:\videos\video1.mpg but when i check my database it shows me as D:videosvideo1.mpg how can i solve that...
here is my code
Dim check As String
Dim check_cmd As New MySqlCommand
Dim checklist As New MySqlDataAdapter
Dim listfile As String
Dim time As String
time = DateAndTime.Now
For L = 0 To bee_shed.Items.Count - 1
listfile = bee_shed.Items.Item(L)
check = "INSERT INTO schedule(id, listname, videofile, videoduration, videotime) VALUES('', '', '" & listfile & "', '' , '" & time & "')"
check_cmd.Connection = con
check_cmd.CommandText = check
checklist.SelectCommand = check_cmd
check_cmd.ExecuteNonQuery()
MsgBox(listfile)
Next
You're concatenating raw SQL statements and not escaping the backslash.
You must use parameters.
For example:
check_cmd.Connection = con
check_cmd.CommandText = "INSERT INTO schedule(id, listname, videofile, videoduration, videotime) VALUES('', '', ?filename, '' , ?time)"
For L = 0 To bee_shed.Items.Count - 1
listfile = bee_shed.Items.Item(L)
check_cmd.Parameters.Clear()
check_cmd.Parameters.Add("filename", MySqlDbType.VarChar, 80).Value = listfile
check_cmd.Parameters.Add("time", MySqlDbType.Something).Value = time
check_cmd.ExecuteNonQuery()
Next