SQL like with multiple textboxes - sql

For my company I have to create a customer database, which I manage over a VB.NET application.
The application has a few textboxes and a button to "Search" for a customer. If I type in the name of a customer the SQL Select statement is working and populating my datagrid.
But I want to be able to type in the name of the customer AND the street where he lives in. What is the best solution for this? using cases? using a lot of If statements?
Here is my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If True Then
Dim Conn As New MySqlConnection
Dim da As MySqlDataAdapter
Dim ds As New DataSet
Dim dt As New DataTable
Dim plz As String = plzTextBox.Text
Conn.ConnectionString = "server=localhost;uid=root;pwd=;database=wws; "
Dim sql As String = String.Empty
If vornameTextBox.Text <> String.Empty Then
sql = "vorname = " & vornameTextBox.Text.Trim
End If
If nachnameTextBox.Text <> String.Empty Then
AddCondition(sql, "nachname LIKE '%" & nachnameTextBox.Text.Trim & "%'")
End If
If emailTextBox.Text <> String.Empty Then
AddCondition(sql, "email LIKE '%" & emailTextBox.Text.Trim & "%'")
End If
If plzTextBox.Text <> String.Empty Then
AddCondition(sql, "plz LIKE '%" & plzTextBox.Text.Trim & "%'")
End If
If sql <> String.Empty Then
da = New MySqlDataAdapter("SELECT id,vorname,nachname,email,plz,strasse,nummer,stiege,stock,tuer FROM kunden WHERE " + sql, Conn)
da.Fill(dt)
DataGridView1.DataSource = dt
End If
Else
DataGridView1.ColumnCount = 1
DataGridView1.Rows.Add("1")
End If
End Sub
Thanks in advance!

You can avoid using lots of if statements if you really want, but all you're doing is shunting a load onto your SQL server instead of having it on the client.
The example here is one where you can use lots of if statements or ternary operators to determine how you build your SQL statement, putting a very light processing load on the client, or you can just insert the text value of each of your fields, followed by a percentage sign and surrounded by single quotes, thus making your SQL server evaluate the contents of those fields when it otherwise wouldn't if the field is blank.
It's possible query plan optimization would remove those superfluous field searches, and maybe it wouldn't. I'm typing this on my phone and so don't have anything available to test with.

Related

how to get datatable if textbox matches your data in database

how can I possibly populate my table if like textbox.text matches from my data inside database.
I'm stuck here, not sure where I did go wrong
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim dbcommand As String
dbcommand = "SELECT * FROM aws_rdp where csn_user like " & txtCSNUser.Text & ""
adt = New OleDbDataAdapter(dbcommand, dbconn)
datatable = New DataTable
adt.Fill(datatable)
DataGridView1.DataSource = datatable
End Sub
Try putting ' before and after the quotation marks surrounding the textbox text. If you're trying to find that text within the text stored in the database you will also need wildcards (%) surrounding it too. Try:
dbcommand = "SELECT * FROM aws_rdp where csn_user like '%" & txtCSNUser.Text & "%'"
Also, as others have stated, look into using parameters in your SQL code as it will help prevent things like SQL injection and is always good practice
Found the answer to my problem by using this code. Anyways, thanks for your time replying on my query, will surely take note of your advises for my future references
Dim dbcommand As String = "SELECT * FROM aws_rdp where csn_user like '%" & txtCSNUser.Text & "%'"
Dim command As New OleDbCommand(dbcommand, dbconn)
Dim adapter As New OleDbDataAdapter(command)
Dim datatable As New DataTable
adapter.Fill(datatable)
DataGridView1.DataSource = datatable
DataGridView1.Columns(0).HeaderText = "ID"
DataGridView1.Columns(1).HeaderText = "IP Address"
DataGridView1.Columns(2).HeaderText = "Username"
DataGridView1.Columns(3).HeaderText = "Password"

How to split a joined column into its seperate columns and use the data? (VB.Net + SQL Management Studio)

This is gonna be somewhat tricky to explain but I'll try to break it down. Note that this is created using VB.Net 2003.
I have a Web page which requires user to input data to save into SQL. They are required to fill in:
Course: {Select via drop-down table} \\ Variable name = Crse
Emp No: {Manually type the number} \\ Variable name = Emp
For the drop down list for Course, the data is obtained from an SQL table 'Course', with the columns:
| Course Code | Course Title |
Once input complete, I can then save the entry into my Emp_Course table in SQL using the query:
Dim updateState As String = "insert into EMP_COURSE" _
& "(Employee_No, CourseCode)" _
& "values('" & Emp.Text & "', " _
& "'"Crse.SelectedItem.ToString & "')"
Previously the drop-down list only needed the show Course Code, but now I'm required to add in the Course Title as well. Another thing to point out is that the Course Code has no fixed length.
Drop-down list sample:
Before:
A001
BX003
After:
A001 - Course A
BX003 - Course BX
Meaning I have to change the logic in populating the drop-down list:
Dim list As New SqlCommand("select CourseCode + ' - ' " _
& "+ CourseTitle as Course from [SQL].[dbo].[Course] " _
& "order by CourseCode", SQLDB)
Now comes my main issue, when I want to save my entry, the program obviously gives an error because the SQL still refers to the Course Code only, while my drop-down list is a Code + Description hybrid.
So since now I've made my course selection, how am I supposed to add to my SQL to update Emp_Course table to tell it to select the Course Code part of my hybrid selection?
I would just go to the Course table and just add a new Code + Title column and refer to that, but I have no authority to modify it and need to work around it.
Any other alternatives I can use?
Dim arr As String() = Crse.SelectedItem.ToString().Split(New Char() {"-"c})
Dim courseCode AS String = Trim(arr(0))
Dim updateState As String = "insert into EMP_COURSE" _
& "(Employee_No, CourseCode)" _
& "values('" & Emp.Text & "', " _
& "'"courseCode & "')"
Comments and explanations in line.
Imports System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Crse.DataSource = CreateDataSource()
'Course is the concatenated string returned from
'the database containing the CourseCode and the CourseTitle
Crse.DataTextField = "Course"
Crse.DataValueField = "CourseCode"
Crse.DataBind()
Crse.SelectedIndex = 0
End If
End Sub
Protected Function CreateDataSource() As DataTable
Dim dt As New DataTable
Using SQLDB As New SqlConnection("Your connection string")
'This selects the CourseCode as a separate column and the string called Course
'containing the CourseCode and the CourseTitle
Using cmd As New SqlCommand("select CourseCode, CourseCode + ' - ' + CourseTitle as Course from [SQL].[dbo].[Course] order by CourseCode", SQLDB)
SQLDB.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
Return dt
End Function
Protected Sub UpdateDatabase()
Using SQLDB As New SqlConnection("Your connection string")
Using cmd As New SqlCommand("insert into EMP_COURSE (Employee_No, CourseCode) values(#EmpNo, #CourseCode);", SQLDB)
'I guessed at the SqlDbType. Check the database for the real data types.
cmd.Parameters.Add("EmpNo", SqlDbType.Int).Value = CInt(Emp.Text)
'Always use parameters to prevent SQL injection
'The SelectedValue will return the CourseCode
cmd.Parameters.Add("#CourseCode", SqlDbType.VarChar).Value = Crse.SelectedValue
SQLDB.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
UpdateDatabase()
End Sub
End Class
Split the value and get the course code as in the following code. Hope it helps.
Dim Str = Crse.SelectedItem.ToString
Dim strArr() As String
strArr = Str.Split(CType("-", Char()))
Dim CourseCode As String = strArr(0).Trim

How do I change data type to fix data type mismatch in criteria expression

I'm trying to get the database value of an item that i put on a listbox to display to the textbox. (vb.net)
My database table name is 'productlog', in this table has 3 columns, productid, productname, and price. I got the productname to display on a listbox that I made, now I am attempting to display the 3 columns on 3 textboxes. However, I get the "data type mismatch in criteria expression" error on my ExecuteReader line. Here's my code:
Public Class shop
Dim provider As String
Dim datafile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Private Sub listboxitems_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listboxitems.SelectedIndexChanged
Dim lbconn As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.Oledb.12.0; Data Source = C:\Users\USER PC\Desktop\orderDB1.accdb")
Dim lbcmd As New OleDb.OleDbCommand("SELECT productid, product, price FROM productlog WHERE productid =' & listboxitems.Text & ' AND product ='" & listboxitems.Text & "' AND price =' & listboxitems.Text & '", lbconn)
Dim lbreader As OleDbDataReader
lbconn.Open()
lbreader = lbcmd.ExecuteReader() 'error appearing right here'
While lbreader.Read
txtproductid.Text = lbreader.GetInt32("productid")
txtproduct.Text = lbreader.GetString("product")
txtprice.Text = lbreader.GetInt32("price")
End While
lbconn.Close()
End Sub
Based on the other questions that I looked up, it might be because that 'productid' and 'price' are both integers and what I'm doing is for a String. I tried to remove the double quotes ('"& txtproductid.Text"') and turn them into 'txtproductid.Text', based from another question I looked up. The another answer that I saw was to convert the string into an integer - 'lbcmd.Parameters.AddwithValue("#productid", ConvertInt32("txtproductid.Text"))' not sure if that's correct but I ended up getting the same error. How do I work around this error? Thanks.
UPDATED CODE:
Private Sub listboxitems_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listboxitems.SelectedIndexChanged
Using lbconn As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.Oledb.12.0; Data Source = C:\Users\USER PC\Desktop\orderDB1.accdb")
Using lbcmd As New OleDb.OleDbCommand("SELECT productid, product, price FROM productlog WHERE productid = ? AND product = ? AND price = ?", lbconn)
'Set your values here. The parameters must be added in the same order that they
'appear in the sql SELECT command
Dim prodidparam As New OleDbParameter("#productid", Me.txtproductid.Text)
Dim prodparam As New OleDbParameter("#product", Me.txtproduct.Text)
Dim priceparam As New OleDbParameter("#price", Me.txtprice.Text)
lbcmd.Parameters.Add(prodidparam)
lbcmd.Parameters.Add(prodparam)
lbcmd.Parameters.Add(priceparam)
'Open the connection
lbconn.Open()
Using lbreader As OleDbDataReader = lbcmd.ExecuteReader()
While lbreader.Read
txtproductid.Text = lbreader.GetInt32("productid").ToString()
txtproduct.Text = lbreader.GetString("product")
txtprice.Text = lbreader.GetInt32("price").ToString()
End While
End Using
End Using
End Using
End Sub
You should not use string concatenation to create your SQL query as you are doing here. That opens you up to a sql injection hack. Instead you should use a parameterized query.
Try something like this (not tested):
Using lbconn As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.Oledb.12.0; Data Source = C:\Users\USER PC\Desktop\orderDB1.accdb")
Using lbcmd As New OleDb.OleDbCommand("SELECT productid, product, price FROM productlog WHERE productid = ? AND product = ? AND price = ?", lbconn)
'Set your values here. The parameters must be added in the same order that they
'appear in the sql SELECT command
lbcmd.Parameters.Add("productid", OleDb.OleDbType.Integer).Value = 1234
lbcmd.Parameters.Add("product", OleDb.OleDbType.VarChar).Value = "value of product"
lbcmd.Parameters.Add("price", OleDb.OleDbType.Integer).Value = 999
'Open the connection
lbconn.Open()
Using lbreader As OleDbDataReader = lbcmd.ExecuteReader()
While lbreader.Read
txtproductid.Text = lbreader.GetInt32("productid").ToString()
txtproduct.Text = lbreader.GetString("product")
txtprice.Text = lbreader.GetInt32("price").ToString()
End While
End Using
End Using
End Using
Since your code is using OleDbConnection you can't use named parameters. Note the question marks in the SELECT statement which server as placeholders for the values.
Note that when using OleDb, you have to add the parameters in the same order as they appear in your sql query.
The Using ... End Using statements ensure that the connection, command and datareader are disposed properly.

Data type mismatch in criteria expression (vb.net, access)

I am trying to take data from the database to the grid. The condition is SELECT * FROM entries WHERE edate='" & Me.dtpDate.Value.Date & "'" But I am getting the error message Data type mismatch in criteria expression. Please see the code below. Also I have attached a screenshot of the error message.
Private Sub dtpDate_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles dtpDate.Leave
'GetDayBookOpeningBalance()
If Me.lblHeading1.Text <> "Daybook entry" Then
Using MyConnection As OleDb.OleDbConnection = FrmCommonCodes.GetConnection(),
MyAdapter As New OleDb.OleDbDataAdapter("SELECT * FROM entries WHERE edate='" & Me.dtpDate.Value.Date & "'", MyConnection)
'Format(Me.dtpDate.Value.Date, "dd/MM/yyyy"))
If MyConnection.State = ConnectionState.Closed Then MyConnection.Open()
Using MyDataSet As New DataSet
MyAdapter.Fill(MyDataSet, "entries")
Me.grdDayBook.DataSource = MyDataSet.Tables("entries")
Dim DataSetRowCount As Integer = MyDataSet.Tables("entries").Rows.Count
If DataSetRowCount > 0 Then
SetGridProperty()
Else
ShowBlankGrid()
FrmCommonCodes.MessageDataNotFound()
End If
End Using
End Using
Else
ShowBlankGrid()
End If
End Sub
This is exactly what could happen for not using parameterized queries.
I bet that your column edate is a column of type Date/Time but you concatenate your Me.dtpDate.Value.Date to the remainder of your sql string command.
This forces an automatic conversion from DateTime to String but the conversion is not as your database would like to see.
If you use a parameter there is no conversion and the database engine understand exactly what you are passing.
Dim sqlText = "SELECT * FROM entries WHERE edate=#dt"
MyAdapter As New OleDb.OleDbDataAdapter(sqlText, MyConnection)
MyAdapter.SelectCommand.Parameters.Add("#dt", OleDbType.Date).Value = Me.dtpDate.Value.Date
....

Need help extracting variables from a While Loop in VB.Net

I'm a novice with my coding so forgive me if my question seems basic but I'm having some trouble extracting my variables from this While Loop in order to then use the results of my SQL query for validation.
This script below is the event handling for a login button on an .aspx form processing an email and login field that will be listed in a correlating MSSQL database:
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub submit_Click(sender As Object, e As EventArgs) Handles submit.Click
Dim Column1 As String
Dim Column2 As String
Dim SQL = "SELECT * FROM Logins WHERE Email='" & email.Text & "' AND Password='" & password.Text & "'"
Dim oSqlDataReader As System.Data.SqlClient.SqlDataReader = Nothing
Using oSqlConnection As New System.Data.SqlClient.SqlConnection("SERVER=[Server Name];UID=[User];PWD=[Pass];DATABASE=[Database Name]")
oSqlConnection.Open()
Using oSqlCommand As New System.Data.SqlClient.SqlCommand(SQL, oSqlConnection)
oSqlDataReader = oSqlCommand.ExecuteReader
While oSqlDataReader.Read
Column1 = oSqlDataReader(name:="Email")
Column2 = oSqlDataReader(name:="Password")
End While
End Using
oSqlConnection.Close()
End Using
If "Column 1 etc."
End if
End Sub
End Class
As far as I can tell my code is working with no errors but every time I try and create an If statement my Variable Column 1 and Column 2 are undeclared making them useless.
If anyone could help with the correct layout for my code or missing areas and an explanation as to where I've gone wrong that'd be great.
If you move the If block inside the loop, do you get closer to the behaviour that you're expecting?
Protected Sub submit_Click(sender As Object, e As EventArgs) Handles submit.Click
Dim Column1 As String
Dim Column2 As String
Dim SQL = "SELECT * FROM Logins WHERE Email='" & email.Text & "' AND Password='" & password.Text & "'"
Dim oSqlDataReader As System.Data.SqlClient.SqlDataReader = Nothing
Using oSqlConnection As New System.Data.SqlClient.SqlConnection("SERVER=[Server Name];UID=[User];PWD=[Pass];DATABASE=[Database Name]")
oSqlConnection.Open()
Using oSqlCommand As New System.Data.SqlClient.SqlCommand(SQL, oSqlConnection)
oSqlDataReader = oSqlCommand.ExecuteReader
While oSqlDataReader.Read
Column1 = oSqlDataReader(name:="Email")
Column2 = oSqlDataReader(name:="Password")
If "Column 1 etc....."
End if
End While
End Using
oSqlConnection.Close()
End Using
End Sub
It could be that your query is returning no rows or that the values returned are dbNull or nothing. I would check the data getting returned and error if appropriate.
Try running the query against the database directly. Are you getting a row back?
To avoid the error, you can declare the string as String.empty
Dim Column1 As String = String.empty
Or, when using it in the if statement check for nothing:
If Column1 Is Not Nothing AndAlso ...
Do not use string concatenation to build your sql query. Instead use sql-parameters to prevent sql injection and other issues.
I must admit that i don't know this syntax: oSqlDataReader(name:="Email"). Use following:
Dim email As String
Dim password As String
Dim sql = "SELECT * FROM Logins WHERE Email=#Email AND Password=#Password"
Using oSqlConnection As New System.Data.SqlClient.SqlConnection("SERVER=[Server Name];UID=[User];PWD=[Pass];DATABASE=[Database Name]")
Using oSqlCommand As New System.Data.SqlClient.SqlCommand(sql, oSqlConnection)
oSqlCommand.Parameters.Add("#Email", SqlDbType.VarChar).Value = email.Text
oSqlCommand.Parameters.Add("#Password", SqlDbType.VarChar).Value = password.Text
oSqlConnection.Open()
Using oSqlDataReader = oSqlCommand.ExecuteReader()
If oSqlDataReader.Read() Then
Dim emailColIndex = oSqlDataReader.GetOrdinal("Email")
Dim pwdColIndex = oSqlDataReader.GetOrdinal("Password")
email = oSqlDataReader.GetString(emailColIndex)
password = oSqlDataReader.GetString(pwdColIndex)
End If
End Using
End Using
End Using ' oSqlConnection.Close() not needed with using '
If email IsNot Nothing AndAlso password IsNot Nothing Then
End If
But instead of initializing two string variables you should implement a Login class that you can initialize and return from the method. You don't want to know the email and the password since you already have them.
Since this is ASP.NET i suggest to look at the available membership provider which are powerful and have a learning curve, but it's definitely worth the time.