Adding the WHERE Statement in the SQL - asp.net

Hi guys after the help in another post I managed to get the following Update SQL statement to work however I wish to add a WHERE.
So I have:
cmd = new SqlCommand("UPDATE Schedule SET Schd_Avaliable = '" + "No" + "'", con);
cmd.ExecuteNonQuery();
And I want to add a Where which looks for the Schd_ID in the table and a schdid which is from a session however with all the punctuation im unsure where to put it.
This is the Where I made:
WHERE Schd_ID = schdid
just unsure where to put that exactly in the line below without it throwing an error:
cmd = new SqlCommand("UPDATE Schedule SET Schd_Avaliable = '" + "No" + "'", con);
cmd.ExecuteNonQuery();
Mark

Try this:
string sql = "UPDATE Schedule SET Schd_Avaliable = 'No' WHERE Schd_ID = #schdid";
cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#schdid", int.Parse(Session["SchdID"].ToString()));
cmd.ExecuteNonQuery();
Modify as needed for your session, and column names.

It is recommended to use Sql Parameters in this situation.
cmd = new SqlCommand(#"UPDATE Schedule
SET Schd_Avaliable = #ScheduleAvailable
WHERE Schd_ID = #ScheduleID", con);
cmd.Parameters.Add(new SqlParameter("#ScheduleAvailable", "No") );
cmd.Parameters.Add(new SqlParameter("#ScheduleID", schdid.ToString()));
cmd.ExecuteNonQuery();

cmd = new SqlCommand("UPDATE Schedule SET Schd_Avaliable = '" + "No" + "' WHERE Schd_ID ='" + schdid + "'", con);
cmd.ExecuteNonQuery();

"UPDATE Schedule SET Schd_Avaliable = '" + "No" + "'" + "WHERE Schd_ID = '" + schdid + '"

Related

SQL Query inserting data into database

I am trying to insert date into database from Session DateValue by converting it into dateTime. The problem i am facing is its accepting the value of april month but when i am entering the value of March its giving error.
Please Help, The Query and the code i have used is as follow:
string a = Session["Date_Value"].ToString();
DateTime date= DateTime.Parse(a);
foreach (GridViewRow g1 in grdData.Rows)
{
//string Status = (g1.FindControl("TextBox1") as TextBox).Text;
//int Status = Convert.ToInt32(Sta);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Real_Attendance"].ConnectionString);
SqlCommand cmd = new SqlCommand("Insert into Attendanc(Stu_id,Status,time,Date,Sub_id) values('" + g1.Cells[3].Text + "',#Status,'" + Session["Time_Value"].ToString() + "', #Date ,'" + Session["Sub_id"].ToString() + "')", con);
//SqlCommand cmd = new SqlCommand("Insert into Attendanc(Stu_id,Status,time,Date,Sub_id) values('" + g1.Cells[3].Text + "','"+ g1.Cells[1].Text +"','" + Session["Time_Value"].ToString() + "','" + Session["Date_Value"].ToString() + "','" + Session["Sub_id"].ToString() + "')", con);
//cmd.Parameters["#Status"].Value = ((Label)(g1.FindControl("Label1"))).Text;
cmd.Parameters.AddWithValue("#Status", ((Label)(g1.FindControl("Label1"))).Text);
cmd.Parameters.AddWithValue("#Date", date.ToShortDateString());
// cmd.Parameters.AddWithValue("#Date", date.ToShortDateString());
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
This is the code I am using to create session. I am creating session at webform3 And using its value at webform4
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
Calendar1.Visible = false;
System.DateTime myDate = new System.DateTime();
myDate = Calendar1.SelectedDate;
txtDate.Text = myDate.ToString("dd/MM/yyyy");
Date = txtDate.Text;
day = Calendar1.SelectedDate.DayOfWeek.ToString();
Response.Write(day);
txtday.Text = day;
Session["Date_Value"] = Date;
//SelectTime();
}
I'm not sure this will solve your problem, but it will improve your code:
string a = Session["Date_Value"].ToString();
DateTime date= DateTime.Parse(a);
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Real_Attendance"].ConnectionString))
{
con.Open();
foreach (GridViewRow g1 in grdData.Rows)
{
using(SqlCommand cmd = new SqlCommand("Insert into Attendanc (Stu_id,Status,time,Date,Sub_id) values (#Stu_id, #Status, #Time, Convert(DateTime, #Date, 103), #Sub_id)", con))
{
cmd.Parameters.AddWithValue("#Stu_id", g1.Cells[3].Text);
cmd.Parameters.AddWithValue("#Status", ((Label)(g1.FindControl("Label1"))).Text);
cmd.Parameters.AddWithValue("#Time", Session["Time_Value"].ToString());
cmd.Parameters.AddWithValue("#Date", date.ToString("dd/MM/yyyy"));
cmd.Parameters.AddWithValue("#Sub_id", Session["Sub_id"].ToString());
cmd.ExecuteNonQuery();
}
}
con.Close();
}
First, I've changed sql statement to have only parameters. It's cleaner, safer, and easier to read and debug this way.
Second, I've changed the value that #Date parameter gets to a specific date format, and informed the database the expected format using the Convert function. this should fix your conversion problem.
Other improvements: I've moved the opening and closing of the connection outside of the foreach loop. there is no need to close and reopen the connection for each command execute. Also, I've moved the SqlConnection and the SqlCommand into using statements, as recommended by microsoft.

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.

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");

Populating a drop down list dynamically in ASP.net, and passing that value to another query?

2 questions for everybody.
1) How can I order the years by their value, it crashes when I use DESC?
2) If I populate my list like so:
string strConn = ConfigurationManager.ConnectionStrings["rde_410978ConnectionString"].ToString();
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select Distinct Year from MonthlySales DESC"; //DESC DOESNT WORK?
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddItems.DataSource = objDs.Tables[0];
ddItems.DataTextField = "Year";
ddItems.DataValueField = "Year";
ddItems.DataBind();
ddItems.Items.Insert(0, "Select");
}
How can I make the year selected appear under ddItems.SelectedItem?
WHERE Year = " + ddItems.SelectedItem + "GROUP BY Name ";
That part of another query doesn't work when I populate my list dynamically, any reasons why/ how can I fix it.
Regards.
EDIT:
To make my second question clearer, after debugging its always selecting the top item in the drop down list not the actual selected item?
First, in your sql you are missing "order by"...use this
"Select Distinct Year from MonthlySales order by Year DESC"
Second, you need to make use of the SelectedValue property to get your dropdown's selected value...as below...
WHERE Year = " + ddItems.SelectedValue + " GROUP BY Name";
Having said that, I strongly recommend you to use..."parameterized" sql...Here is an example on how you could enable parameterized sql query...
Give me parameterized SQL, or give me death
Update:
Looks like you are binding your dropdown on every post back...you may try this...
if (!Page.IsPostBack && objDs.Tables[0].Rows.Count > 0)
{
ddItems.DataSource = objDs.Tables[0];
ddItems.DataTextField = "Year";
ddItems.DataValueField = "Year";
ddItems.DataBind();
ddItems.Items.Insert(0, "Select");
}
Ans 1)
cmd.CommandText = "Select Distinct Year from MonthlySales ORDER BY 1 DESC"
You are missing order by. Here it is.
"Select Distinct Year from MonthlySales order by Year DESC";
For your second part you can do this. Please mind the space in " GROUP BY Name"
WHERE Year = " + ddItems.SelectedItem.Text + " GROUP BY Name ";
using (SqlConnection con = new SqlConnection(strConn))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select Distinct Year from MonthlySales Order By DESC";
using (DataSet objDs = new DataSet())
{
using (SqlDataAdapter dAdapter = new SqlDataAdapter())
{
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddItems.DataSource = objDs.Tables[0];
ddItems.DataTextField = "Year";
ddItems.DataValueField = "Year";
ddItems.DataBind();
ddItems.Items.Insert(0, "Select");
}
}
}
}
}

The multi-part identifier could not be bound

this error appear when run this code
SqlConnection con = new SqlConnection(#"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=meral10;Integrated Security=True");
SqlCommand comsel = new SqlCommand("SELECT email from reg where email ="+email_tb.Text,con);
con.Open();
comsel.ExecuteNonQuery();
con.Close();
if (comsel == null)
{
birthday = day_ddl.Text + "/" + month_ddl.Text + "/" + year_ddl.Text;
SqlCommand com = new SqlCommand("INSERT INTO reg(first_name,last_name,email,email_ver,pass,gender,birthday) values(#fn,#ln,#email,#reemail,#pass,#gen,#birth)", con);
con.Open();
com.Parameters.AddWithValue("#fn", firstname_tb.Text);
com.Parameters.AddWithValue("#ln", lastname_tb.Text);
com.Parameters.AddWithValue("#email", email_tb.Text);
com.Parameters.AddWithValue("#reemail", reemail_tb.Text);
com.Parameters.AddWithValue("#pass", pass_tb.Text);
com.Parameters.AddWithValue("#gen", gender_ddl.SelectedItem.Text);
com.Parameters.AddWithValue("#birth", birthday);
com.ExecuteNonQuery();
con.Close();}
Try putting quotes around email_tb.Text, like this:
"SELECT email from reg where email ='" + email_tb.Text + "'"
Try:
SqlCommand comsel = new SqlCommand("SELECT email from reg where email ='" + email_tb.Text + "'", con)
E.g. your string literal need to be in quotes. Better yet, use a SqlParameter!

Resources