If/Else Statements in VB.NET (SQL) Query? - asp.net

I just wanted to know what's the best way to add If/Else statements in a SQL query within VB.Net code?
This is my current query (doesn't work):
SELECT
FIRSTNAME, LASTNAME
FROM
TBL_USERS
ORDER BY
If(SortSelect() Is ""lastname"", LASTNAME, FIRSTNAME)
Thanks in advance.

My opinion about this is to NEVER put the IF in the SQL statement. It makes it too hard to read. Probably because it's all on the same line.
In your case, there's only one, but when you got many conditions, it gets almost impossible to read.
You should declare a string for your condition like this
Dim strQuery as string
Dim strOrderBy as string
If(SortSelect() = "lastname") then
strOrderBy = "Order By lastname"
Else
strOrderBy = "Order By firstname"
endif
strQuery = "SELECT FIRSTNAME, LASTNAME FROM TBL_USERS " & strOrderBy

you could try something like this:
SELECT FIRSTNAME, LASTNAME
FROM TBL_USERS
ORDER BY Case when <SortSelect>= 'lastname' then LASTNAME else FIRSTNAME end

Dim sql as string = "SELECT FIRSTNAME, LASTNAME FROM TBL_USERS ORDER BY "
if (SortSelect() = "lastname")
sql = sql & "lastname"
else
sql = sql & "firstname"
end if

Related

Updating Password in sql database using text-box

using ASP.NET & VB.NET i trying to update the user password, where it is equals to the sessionID
Database using is SQL Local.
here is the vb .net code
Dim pass As String
pass = tboxConFirmPass.Text
Dim connce As SqlCeConnection = New SqlCeConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ToString())
connce.Open() 'make the connection to DB
Dim sqlCommand As String = "UPDATE [tbCustomer] SET [Password] = ('" _
+ tboxConFirmPass.Text + "', '" + "WHERE [CustomerID] = #CustomerID" + "')"
Dim cmd As SqlCeCommand = New SqlCeCommand(sqlCommand, connce)
cmd.ExecuteNonQuery()
connce.Close()
MsgBox("Your Password has been chaged.")
End Sub
here is the SqlDataSource
UpdateCommand="UPDATE [tbCustomer] SET [Password] = #Password WHERE [CustomerID] = #CustomerID">
Error = There was an error parsing the query. [ Token line number = 1,Token line offset = 42,Token in error = , ]
Right, your query needs to be changed thus:
Dim sqlCommand As String = "UPDATE [tbCustomer] SET [Password] = '" _
& Replace(tboxConFirmPass.Text, "'", "''") & "' WHERE [CustomerID] = #CustomerID"
I've sorted your brackets and quotes mismatches out, changed the string concatenation operator to & and put an escape in to reduce the possibility of SQL injection vulnerability (if someone puts a single quote in their password, your query will no longer fall over, or worse).
To set a value for #CustomerID you need to add a SQL Parameter to the command object. If you don't give it a value you'll get the error mentioned in your comment. Alternatively you can concatenate the value like you do with the password:
Dim sqlCommand As String = "UPDATE [tbCustomer] SET [Password] = '" _
& Replace(tboxConFirmPass.Text, "'", "''") & "' WHERE [CustomerID] = " & CustomerID
Note that you will need to use a variable that is initialised with the ID of the customer whose password is being changed.

Is it possible to append text to a textbox using a for each statement?

I am using the code below to read through each record and get the data. Is there a way I can append the text eachtime to my summarytextbox so it will show all the records/add them one by one?
Dim str As String = Session("List")
For Each s As String In str.Split(","c)
SummaryTextBox.Text = Session("FirstName") & " " & Session("LastName")
Next
I like to use the StringBuilder:
Dim str As String = Session("List")
Dim sb As New Text.StringBuilder()
For Each s In str.Split(","c)
sb.Append(s)
Next
SummaryTextBox.Text = sb.ToString()
... and of course, you can use whatever format you want to display the concatenated results.
EDIT: Like Tim alluded to, I'm not sure what the difference between the List and FirstName and LastName session variables, so I'm just appending the s until further clarification is made by the OP.
Yes.
Dim str As String = Session("List")
For Each s As String In str.Split(","c)
SummaryTextBox.Text &= Session("FirstName") & " " & Session("LastName") & ", "
Next
I'm not sure how that list is related to the firstname and lastname. However, this might give you an idea:
Dim firstName = DirectCast(Session("FirstName"), String)
Dim lastName = DirectCast(Session("LastName"), String)
Dim query = From s In DirectCast(Session("List"), String).Split(","c)
Select String.Format("{0} {1}: {2}", firstName, lastName, s)
SummaryTextBox.Text = String.Join(Environment.NewLine, query)
Stringbuilder is the preferred method. String is immutable, therefor every time a string is appended with & " ", a new string is created. StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed on it.

UPDATE statement in asp.net doesn't do anything

I am making a settings page on my website where the user can change his email adress, name, etc.
The problem is the update statement, it doesn't work, because nothing has changed in the database, but it doesn't give me an error, so I don't know what's up.
When I check with breakpoints it shows that the parameters are getting the right values, and when i search on the internet I can't find anyone with the same problem.
I will paste the code of the update below:
Dim CmdUpdate As New OleDbCommand
Dim Sqlstatement As String = "UPDATE tblUsers SET firstname = #firstname, lastname = #lastname, userPassword = #userPassword, email = #email, avatar = #avatar WHERE userID = #userID;"
CmdUpdate.Connection = dbConn.cn
CmdUpdate.CommandText = Sqlstatement
CmdUpdate.Parameters.AddWithValue("firstname", txtFirstName.Text)
CmdUpdate.Parameters.AddWithValue("lastname", txtLastName.Text)
CmdUpdate.Parameters.AddWithValue("userID", Session("userID"))
If txtPassword.Text = "" Then
CmdUpdate.Parameters.AddWithValue("userPassword", Session("hashedpass"))
Else
CmdUpdate.Parameters.AddWithValue("userPassword", hash(txtPassword.Text))
End If
CmdUpdate.Parameters.AddWithValue("email", txtEmail.Text)
CmdUpdate.Parameters.AddWithValue("avatar", strAvatar)
dbConn.cn.Close()
dbConn.cn.Open()
CmdUpdate.ExecuteNonQuery()
dbConn.cn.Close()
Is it possible that the userid column just doesn't match, so your WHERE clause matches zero records and nothing gets updated? That could be caused by a number of things -- whitespace, character encoding, and so forth.
You just have to include the "#" in your parameter add statements :
CmdUpdate.Parameters.AddWithValue("#firstname", txtFirstName.Text)
...and so on...
You missed the '#'s in the sql-parameters:
CmdUpdate.Parameters.AddWithValue("#firstname", txtFirstName.Text)
etc.
Use
CmdUpdate.Parameters.AddWithValue("#firstname", txtFirstName.Text)
You were missing to add '#' in AddWithValue()
See Tutorial here

Update SQL Server tables using textboxes

I'm programming an education website using asp.net vb.net and SQL Server. I have 4 stackholders, if any body log in in his profile he will see his information
If he wants to update them he just change the textboxes then click update
My problem is how to update.
I wrote a method to update but it always show me a syntax error in the query. I made sure there is no problem. I'm updating two tables and I made to sql statements!
My qustion is can I Insert instead of update?
If not: how to upade one record based on the session I have?
please help me
this my code
' Private Sub UpdateInfo(ByVal USER_ID As Integer)
'Dim User As Integer = USER_ID
'Dim sql1 As String = "UPDATE AdminCoordinatorInformation SET MobileNumber =" + tbmobile.Text + ", HomeNumber=" + tbhome.Text + ", AltRelation = " + DDLRelationShip.SelectedValue + ", AlTitle = " + DDLTitle.SelectedValue + ", AltName = " + tbemname.Text + ", AltMobile = " + tbemmobile.Text + " WHERE USER_ID = User)"
'Dim sql2 As String = "UPDATE DIP_USERS SET USER_Email=" + tbEmail.Text.Trim + " WHERE USER_ID = User)"
' Try
' Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("mydbConnectionString").ConnectionString)
' Dim cmd1 As New SqlCommand(sql1, conn)
' Dim cmd2 As New SqlCommand(sql2, conn)
' cmd2.Parameters.AddWithValue("#FirstName", tbname.Text)
' cmd2.Parameters.AddWithValue("#USER_PASSWORD", tbnewpassword.Text)
' cmd2.Parameters.AddWithValue("#USER_Email", tbEmail.Text)
' cmd1.Parameters.AddWithValue("#MobileNumber", tbmobile.Text)
' cmd1.Parameters.AddWithValue("#HomeNumber", tbhome.Text)
' cmd1.Parameters.AddWithValue("#AltRelation", DDLRelationShip.SelectedValue)
' cmd1.Parameters.AddWithValue("#AlTitle", DDLTitle.SelectedValue)
' cmd1.Parameters.AddWithValue("#AltName", tbemname.Text)
' cmd1.Parameters.AddWithValue("#AltMobile", tbemmobile.Text)
' conn.Open()
'Dim ra As Integer = cmd1.ExecuteNonQuery()
'Dim ra1 As Integer = cmd2.ExecuteNonQuery()
'cmd1.Dispose()
'cmd2.Dispose()
' conn.Close()
' Catch ex As Exception
' MsgBox(ex.Message)
' End Try
'End Sub
you have not specified your parameters in your query, you're directly concatenating the values of controls inside your query. And still you have added parameters.
Firstly, do not concatenate your sql query like that, its prone to SQL Injection.
construct your query like this:
Dim sql1 As String = "UPDATE AdminCoordinatorInformation SET
MobileNumber =#MobileNumber,
HomeNumber=#HomeNumber,
AltRelation = #AltRelation,
AlTitle = #AlTitle,
AltName =#AltName,
AltMobile = #AltMobile
WHERE USER_ID = #User"
Dim sql2 As String = "UPDATE DIP_USERS SET
USER_Email=#USER_Email
WHERE USER_ID = #User"
and also, add this parameter too
cmd1.Parameters.AddWithValue("#User", USER_ID)
cmd2.Parameters.AddWithValue("#User", USER_ID)
And one very important thing. you need to assign proper datatype to your columns in the query i.e.
remember these things.
txtBox.Text returns String value, you might need to convert it to Int32 using Convert.Int32 or you need to wrap it in single quote, based totally upon datatype of your column
Put parameters which you declare in your SQL Command query:
"UPDATE AdminCoordinatorInformation SET MobileNumber=#MobileNumber,HomeNumber=#homeNumber...
You get syntax error because your string data in sql query must be wrapped with "'".
"UPDATE AdminCoordinatorInformation SET MobileNumber='0987654321',....
Note: creating sql queries by concating query with user inputs ("...SET MobileNumber='" + txtbox.Text + "',...") is not good/dangerous practice because of SQL Injection

An example of advanced database search

im looking for an example script. I saw one yesterday but for the life of me I can't find it again today.
The task I have is to allow the user to search 1 database table via input controls on an aspx page where they can select and , or , equals to combine fields, generating the sql on the fly with concat/stringbuilder or similar. (it runs behind the corp firewall)
Please can someone point me in the right direction of an example or tutorial
I've been working on the page, but have run into problems. Here is the Page_load;
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sql As String = ("Select * From Table Where ")
'variables to hold the and or values between fields
Dim andor1v As String = AndOr1.SelectedValue.ToString()
Dim andor2v As String = AndOr2.SelectedValue.ToString()
Dim andor3v As String = AndOr3.SelectedValue.ToString()
Dim andor4v As String = AndOr4.SelectedValue.ToString()
Dim andor5v As String = AndOr5.SelectedValue.ToString()
Dim andor6v As String = AndOr6.SelectedValue.ToString()
'variables to stop web control inputs going direct to sql
Dim name As String = NameSearch.Text.ToString()
Dim email As String = EmailSearch.Text.ToString()
Dim city As String = CitySearchBox.Text.ToString()
Dim province As String = ProvinceSelect.SelectedValue.ToString()
Dim qualifications As String = QualificationsObtained.Text.ToString()
Dim competencies As String = CompetenciesDD.SelectedValue.ToString()
Dim expertise As String = Expertiselist.SelectedValue.ToString()
If NameSearch.Text IsNot String.Empty Then
sql += "Surname LIKE '%" & name & "%' "
End If
If EmailSearch.Text IsNot String.Empty Then
sql += andor1v & " Email LIKE '%" & email & "%' "
End If
If CitySearchBox.Text IsNot String.Empty Then
sql += andor2v & " City LIKE '%" & city & "%' "
End If
If QualificationsObtained.Text IsNot String.Empty Then
sql += andor3v & " (institutionquals1 LIKE '%" & qualifications & "%') OR " & _
"(institutionquals2 LIKE '%" & qualifications & "%') OR " & _
"(institutionquals3 LIKE '%" & qualifications & "%') OR " & _
"(institutionquals4 LIKE '%" & qualifications & "%') "
End If
Dim selectedrow As String = CompetenciesDD.SelectedValue.ToString
Dim selectedquals As String = NQFlevel.SelectedValue.ToString
If CompetenciesDD.SelectedValue.ToString IsNot "0" And selectedquals = 0 Then
sql += (selectedrow & " = 1 ")
ElseIf selectedrow = "assessortrue" And selectedquals IsNot "0" Then
sql += andor4v & (" assessortrue=1 and assessorlvl=" & selectedquals)
ElseIf selectedrow = "coordinatortrue" And selectedquals IsNot "0" Then
sql += andor4v & ("coordinatortrue=1 and coordinatorlvl=" & selectedquals)
ElseIf selectedrow = "facilitatortrue" And selectedquals IsNot "0" Then
sql += andor4v & ("facilitatortrue=1 and facilitatorlvl=" & selectedquals)
ElseIf selectedrow = "moderatortrue" And selectedquals IsNot "0" Then
sql += andor4v & ("moderatortrue=1 and moderatorlvl=" & selectedquals)
ElseIf selectedrow = "productdevelopertrue" And selectedquals IsNot "0" Then
sql += andor4v & ("productdevelopertrue=1 and productdeveloperlvl=" & selectedquals)
ElseIf selectedrow = "projectmanagertrue" And selectedquals IsNot "0" Then
sql += andor4v & ("projectmanagertrue=1 and projectmanagerlvl=" & selectedquals)
End If
Response.Write(sql)
End Sub
After an hours tinkering the code is now looking as it does above ^
Now the problem im faced with is if a user does not enter a value for surname (the first field) but does enter a value for email (or any subsequent fields), the sql produced has an extra and like this;
Select * From Table Where And Email LIKE '%test%'
I'm also looking for a way to take the OR option into account. Do you think this should be done as Martin says where the whole query is either an and or an or and not a mix of the 2? Then I should be able to take out all the and/or drop downs?
Thanks.
NB: I'm not really looking for comments on how I should parameterise or about sql injection.
Regarding your issue with users not selecting an option you could just remove the "please select" and have it default to "and"
Also what is the desired behaviour if they select a mix of ANDs and ORs?
By default the ANDs will be evaluated first in the absence of any brackets
http://msdn.microsoft.com/en-us/library/ms186992.aspx
So if they enter
name="Fred" or email="blah" and
city="london" and province="xyz" or
qualifications="Degree"
I'm not really sure what the desired semantics would be?
Is it
(name="Fred" or email="blah") and
city="london" and (province="xyz" or
qualifications="Degree")
or
(name="Fred" or (email="blah" and
city="london") and province="xyz") or
qualifications="Degree"
Or something different? Maybe you should restrict them to AND or OR for the whole query or allow them to disambiguate either by typing in advanced search syntax with brackets or by providing a query builder UI.
To avoid sql injection and allow a dynamic search I would probably write a stored procedure something like this. If nothing is selected send DBNull.Value in the ado.net parameters collection as the parameter value. With this approach you can check any columns you want and if they are not selected by the user they will be ignored.
EDIT: I just saw that you are not allowed to use stored procedures. I changed my answer below to show a parameterized sql statement
SELECT * FROM TABLE
WHERE ([name] = #name OR #name IS NULL)
AND (email = #email OR #email IS NULL)
AND (city = #city OR #city IS NULL)
AND (province = #province OR #province IS NULL)
AND (qualifications = #qualifications OR #qualifications IS NULL)
AND (competencies = #competencies OR #competencies IS NULL)
AND (expertise = #expertise OR #expertise IS NULL)
Concat strings to build a query is never a good idea. You should use a stored procedure or parametrized queries
I have done this "dynamic" type query interface on classic asp.
The advice that I give to you is that you are trying to do the whole query in one page load so...
Look to "building" the query via a "wizard" type interface - either ajax for the newness or simple multiple pages for each part of the query building.
This is essence gives you "persitance" via what ever means you have (session, dbstore, cookie etc) for each part of the query and you have can sanity check each part of the query as you build.
Dim sql As String = ("Select * From Table Where **1=1**")
'variables to hold the and or values between fields
Dim andor1v As String = AndOr1.SelectedValue.ToString()
Dim andor2v As String = AndOr2.SelectedValue.ToString()
Dim andor3v As String = AndOr3.SelectedValue.ToString()
Dim andor4v As String = AndOr4.SelectedValue.ToString()
Dim andor5v As String = AndOr5.SelectedValue.ToString()
Dim andor6v As String = AndOr6.SelectedValue.ToString()
'variables to stop web control inputs going direct to sql
Dim name As String = NameSearch.Text.ToString()
Dim email As String = EmailSearch.Text.ToString()
Dim city As String = CitySearchBox.Text.ToString()
Dim province As String = ProvinceSelect.SelectedValue.ToString()
Dim qualifications As String = QualificationsObtained.Text.ToString()
Dim competencies As String = CompetenciesDD.SelectedValue.ToString()
Dim expertise As String = Expertiselist.SelectedValue.ToString()
If NameSearch.Text IsNot String.Empty And andor1v IsNot "0" Then
sql += "**and** Surname LIKE '%" & name & "%' "
ElseIf NameSearch.Text IsNot String.Empty And andor1v Is "0" Then
sql += "**or** Surname LIKE '%" & name & "%' "
End If
....additional logic here.....
Response.Write(sql)
End Sub
note the ** parts. 1=1 evaluates to true on most DBMS. This allows you to just start concatenating your or / ands on to it without worrying about ()'s

Resources