Search command using session variable asp.net - asp.net

I have a name stored in a session variable called "name".
I have written the statement:
da = new SqlDataAdapter("Select empID from emp where empFirstName=' "+
Session["name"].ToString() + " '", connstring);
da.Fill(ds);
I have verified that the session variable is not empty. Yet i am not able to fetch the empID of the record that exists in the table. Is this statement correct?

You have spaces at the beginning and end of the string variable in SQL statement.
Try this, it should work:
da = new SqlDataAdapter("Select empID from emp where empFirstName='"+
Session["name"].ToString() + "'", connstring);

The problem was with the spaces over here:
' " + Session["name"].ToString() + " '"
^ ^
| |
that is why the values are suffixed and prefixed by a blank space.
You should try:
da = new SqlDataAdapter (
"Select empID from emp where empFirstName='" + Session["name"].ToString() + "'",
connstring);
da.Fill(ds);

Related

Error: An expression of non-boolean type specified in a context where a condition is expected

I want to pass three query string variables, which ars DateFrom, DateTo and UserName. When I call that the variable, it shows an error:
'An expression of non-boolean type specified in a context where a condition is expected, near 'admin'.'".
How can I resolve the issue? Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
strDate = Convert.ToDateTime(Request.QueryString["DateFrom"]);
endDate = Convert.ToDateTime(Request.QueryString["DateTo"]);
UserName = Convert.ToSingle(Request.QueryString["UsName"]);
string UserName = Request.QueryString["UsrName"];
string sql;
sql = ("SELECT * FROM tblReport WHERE Date between'" + strDate + "'and'" + endDate + "'and'" + UserName + "'");
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
DataTable dt = new DataTable();
DataSet dst = new DataSet();
sda.Fill(dst, "tblReport");
crypt.Load(#"D:\My Project\Asp.Net\ITApplication\ITApplication\CrystalReport.rpt");
crypt.SetDataSource(dst);
CrystalReportViewer1.ReportSource = crypt;
}
you are missing something in your where clause... should be like this:
WHERE Date BETWEEN '<FromDate>' AND '<ToDate>'
AND UserName = '<UserName>'
Your SQL string is not formatted well.
Put spaces near yout and operators and use () in your between:
sql = ("SELECT * FROM tblReport WHERE [Date] between ('" + strDate + "' and '" + endDate + "') and UserName='" + UserName + "'");
Side note:
Using SQL strings with concatenating values like this is a very bad idea. It exposes you to SQL Injections, and overall a bad practice. Please consider using Command.Parameters:
SqlCommand Command = new SqlCommand("SELECT * FROM tblReport WHERE [Date] between (#strDate and #endDate) and UserName=#UserName");
Command.Parameters.Add(new SqlParameter("strDate", strDate));
Command.Parameters.Add(new SqlParameter("endDate", endDate));
Command.Parameters.Add(new SqlParameter("UserName", UserName));

asp.net multiple sqlcommands in one GridView

I have problem to show multiple sql command in one GridView. Maybe I don't need two sqlcommands to show from two tables but I don't know how to do.
The first command is to get all employees that have vacation between two dates.
The second command I am using it to retrieve dates by ID. But I don't know how to Bind them both to one GridView to show as attached image. Thank you in advance.
What I get Now is
Albert 2016-03-16
Albert 2016-03-17
Albert 2016-03-18
Johanna 2016-03-17
Johanna 2016-03-18
Eric 2016-03-18
Instead of
Albert 2016-03-16, 2016-03-17, 2016-03-18
Johanna 2016-03-17, 2016-03-18
Eric 2016-03-18
I think I have to loop between two While statment and maybe with one sqlcommand?
My code is:
using (SqlConnection con = new SqlConnection(connection))
{
con.Open();
SqlCommand cmd = new SqlCommand(" SELECT distinct E.EmployeeId, E.FirstName
FROM Employee E INNER JOIN Vacation V ON E.EmployeeId = V.EmployeeId " +
" WHERE ((V.Dates >= #Start AND V.Dates <= #End) ) ", con);
cmd.Parameters.AddWithValue("#Start", (Calendar1.SelectedDates[0]).Date.ToShortDateString());
cmd.Parameters.AddWithValue("#End", (Calendar1.SelectedDates[Calendar1.SelectedDates.Count - 1]).Date.ToShortDateString());
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
Response.Write((dr[1]).ToString() + " "); // Cheack if retrivs Employeename
// Now By Id I want to get all dates belong to specifik employee
SqlCommand cmd2 = new SqlCommand(" SELECT V.Dates FROM Vacation V " +
" WHERE ((V.Dates >= #Start AND V.Dates <= #End) ) ", con);
cmd2.Parameters.AddWithValue("#Start", (Calendar1.SelectedDates[0]).Date.ToShortDateString());
cmd2.Parameters.AddWithValue("#End", (Calendar1.SelectedDates[Calendar1.SelectedDates.Count - 1]).Date.ToShortDateString());
cmd2.Parameters.AddWithValue("#EmployeeId", Convert.ToInt32(dr[0]));
using (SqlDataReader dr2 = cmd2.ExecuteReader())
{
while (dr2.Read())
{
//Response.Write(Convert.ToDateTime(dr2[0]));
GridView7.DataSource = cmd2.ExecuteReader();
GridView7.DataBind();
}
}
Response.Write("<br/>");
}
}
con.close();
}
GridView7.DataSource = cmd.ExecuteReader();
GridView7.DataBind();
The FOR XML PATH syntax allows your query to group several values in a single one:
SELECT
E.EmployeeId,
E.FirstName,
REPLACE(STUFF((
SELECT
COALESCE('¶' + V.Dates, '')
FROM
Vacation V
WHERE
V.EmployeeId = E.EmployeeId AND V.Dates >= #Start AND V.Dates <= #End
FOR XML PATH('')), 1, 1, ''), '¶', ', ') AS VacationDates
FROM
Employee E
You can replace the ', ' separator by something else if you want.
Note: Sorry for the multipe edits. I am just not sure how you connect the employees, vacations and dates. This piece of code basically shows the idea for the FOR XML PATH syntax.

is this code vulnerable to SQL Injections?

page loads you have to fill some text boxes and then click add:
tbSpyReports spyReport = new tbSpyReports();
spyReport.sgCityLevel = Convert.ToInt32(tbCityLevel.Text);
spyReport.sgCityName = tbCityName_insert.Text;
....
spyReport.insert();
Response.Redirect(Request.RawUrl);
SqlConnection con = ikaConn.getConn();
SqlCommand command = new SqlCommand("INSERT INTO spyReports(cityName, playerName, cityId, islandId, cordX, cordY, " + "cityLevel, cityWall, cityWarehouse, Wood, Wine, Marble, Crystal, Sulfur, hasArmies) VALUES(" + "#cityName, #playerName, #cityId, #islandId, #cordX, #cordY, " + "#cityLevel, #cityWall, #cityWarehouse, #Wood, #Wine, #Marble, #Crystal, #Sulfur, #hasArmies)", con);
command.Parameters.Add(new SqlParameter("cityName", this.cityName));
command.Parameters.Add(new SqlParameter("playerName", this.playerName));
....
command.ExecuteNonQuery();
command.Dispose();
It shouldn't be vulnerable to traditional SQL injection of this form:
statement = "SELECT * FROM users WHERE name ='" + userName + "';"
as you're using parameterized queries.

Get results from two tables - asp.net/SQL Server 2008R2

I have a search form with 2 fields(first name and last name) from one table (Just has person's information) and 4 (Incident number, date, place, created by) from the other (has one or more incidents for the person in the first table) linked through foreign key(nameID). I think the problem is what kind of join to use and how to use the WHERE clause.
Thanks.
More information:
#Tim - Isn't the user input into one or more fields the filter or it is the WHERE Clause? The user doesn't have to fill in all the fields. Thats where I am getting lost. The user is trying to find the incident to update it. Does this help?
Also I have to use "Like%LName%" in the Where clause to get all the names if they don't enter the entire name.
My query looks like this:
Protected Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
Dim strSearch As String
strSearch = "SELECT tblPatron.LName, tblPatron.FName, tblIncident.CreatedBy, "
strSearch = strSearch + "tblIncident.Inci_ID, tblIncident.Inci_date, tblIncident.Inci_type, tblIncident.Library, "
strSearch = strSearch + "tblIncident.PatronName, tblIncident.Location "
strSearch = strSearch + "FROM tblPatron INNER JOIN tblIncident ON tblPatron.PatronID = tblIncident.PatronID "
strSearch = strSearch + "WHERE "
strSearch = strSearch + "(tblPatron.LName Like '%" + txtLName.Text.ToString() + "%') "
strSearch = strSearch + "AND (tblPatron.FNAME Like '%" + txtFName.Text.ToString() + "%')"
strSearch = strSearch + "AND (tblIncident.Inci_ID ='" + strInciNum.Text.ToString() + "')"
strSearch = strSearch + "AND (tblIncident.Inci_date = '" + txtInciDate.Text.ToString() + "')"
strSearch = strSearch + "AND (tblIncident.Inci_type = '" + ddInciCat.SelectedValue.Trim + "')"
strSearch = strSearch + "AND (tblIncident.Library = '" + ddLib.SelectedValue.Trim + "')"
SearchPDS.SelectCommand = strSearch
SearchPDS.DataBind()
GridSearchResults.DataBind()
GridSearchResults.Visible = True
End Sub
do this:
SELECT A.FirstName, A.LastName, B.IncidentNumber, B.Date, B.Place, B.CreatedBy
FROM Name A INNER JOIN Incident B
ON A.NameID = B.NameID
SELECT firstname, lastname, incidentnumber, date, place, createdby
FROM name n
INNER JOIN incident i ON n.nameID = i.nameID
WHERE firstname LIKE '%'+#firstname+'%'
AND lastname LIKE '%'+#lastname+'%'
Where #firstname and #lastname are parameters containing values from the search fields
In your string concatenation style, just add txtFName.Text.ToString() and txtLName.Text.ToString() into the string in place of those parameters.
I took the suggestion of logixologist. On the click event I added multiple if statements to check for the null value and then add build the query string. At the same time I made one of the dropdown to be a default value instead of "Select" and that would be my starting Where parameter. This works for me now. There might be a better way of writing the query, I am just beginner with asp.net
Thanks for all your replies. I love this forum.
What you need is dynamic sql. Basically you start by declaring a varchar(max)
DECLARE #Sql as varchar(max)
Then you will set it to the base SQL Statement:
SET #SQL = 'SELECT A.FirstName, A.LastName, B.IncidentNumber, B.Date, B.Place, B.CreatedBy
FROM Name A INNER JOIN Incident B
ON A.NameID = B.NameID where lastname IS NOT null ' -- PUT IN A WHERE CLAUSE THAT WILL ALWAYS BE TRUE
---Here is the concept in pseudo code
IF #lastname is not null
BEGIN
SET #SQL = #SQL + 'and lastname = '%' + #lastname + '%'
END
IF #FIRSTNAMEis not null
BEGIN
SET #SQL = #SQL + 'and FIRSTNAME = '%' + #FIRSTNAME+ '%'
END
At the end
EXEC (#SQL)
This will give you any option they put in.

Confused about database select query

I am following a session tutorial .The problem is this part.
OleDbCommand fecth = new OleDbCommand(
"SELECT * FROM YONETICI Where YNAME'" +
txtad.Text + "' and YPASS'" + txtpass.Text + "' ",
con);
At this part I am getting an exception named Incorrect syntax -Missing operator(I have tried to translate)
this is the rest of code
OleDbConnection con = new OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+
Server.MapPath("App_Data\\db.accdb"));
con.Open();
OleDbCommand fecth = new OleDbCommand(
"SELECT * FROM YONETICI Where YNAME'" +
txtad.Text + "' and YPASS'" + txtpass.Text + "' ",
con);
OleDbDataReader dr=fecth.ExecuteReader();
if(dr.Read()){
Session.Add("value",txtad.Text);
Response.Redirect("Default.aspx");
You need an equals operator.
OleDbCommand fecth = new OleDbCommand(
"SELECT * FROM YONETICI Where YNAME = '" +
txtad.Text +
"' and YPASS = '" +
txtpass.Text + "' ",
con);
Try that. I added two equals operators to your query.
exactly,you need to add 2 equal sign but i prefer to write your query in a better way
,this one will replace the #Parameter with the value like code below with
fetch.Parameters.addWithValue()
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+Server.MapPath("App_Data\\db.accdb"));
con.Open();
OleDbCommand fecth = new OleDbCommand("SELECT * FROM YONETICI Where YNAME='#txtad' and YPASS='#txtpass'", con);
fecth.Parameters.AddWithValue("#txtad",txtad.Text);
fecth.Parameters.AddWithValue("#txtpass",txtpass.Text);
OleDbDataReader dr=fecth.ExecuteReader();
if(dr.Read()){
Session.Add("value",txtad.Text);
Response.Redirect("Default.aspx");

Resources