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!
Related
I'm working with ASP.net. I'm trying to fetch data from a table "Pret" and display them in view. The following code is working properly:
public ActionResult Details(int id)
{
StringBuilder errorMessages = new StringBuilder();
using (SqlConnection con = new SqlConnection(chaineConnexion))
{
DataTable tabRetard = new DataTable();
con.Open();
SqlDataAdapter adp = new SqlDataAdapter();
SqlCommand command = new SqlCommand(
"SELECT Livre.titre,Membre.nom, " +
"FORMAT(Retard.DatePret, 'yyyy-MM-dd') as DatePret, Nbjour FROM Retard " +
"LEFT JOIN Livre ON Retard.Id_livre = Livre.Id " +
"LEFT JOIN Membre ON Retard.Id_membre = Membre.Id", con);
adp.SelectCommand = command;
adp.Fill(tabRetard);
return View(tabRetard);
}
}
Now I'm trying to add a parameter to the query like that, but it throws an exception
System.Data.SqlClient.SqlException : 'Incorrect syntax near 'Retard'
I can't figure out what the problem is !
public ActionResult Details(int id)
{
StringBuilder errorMessages = new StringBuilder();
using (SqlConnection con = new SqlConnection(chaineConnexion))
{
DataTable tabRetard = new DataTable();
con.Open();
SqlDataAdapter adp = new SqlDataAdapter();
SqlCommand command = new SqlCommand(
"SELECT Livre.titre, Membre.nom, " +
"FORMAT(Retard.DatePret, 'yyyy-MM-dd') as DatePret, Nbjour FROM Retard " +
"LEFT JOIN Livre ON Retard.Id_livre = Livre.Id " +
"LEFT JOIN Membre ON Retard.Id_membre = Membre.Id" +
"WHERE Retard.Id_membre = #Id_membre", con);
command.Parameters.AddWithValue("#Id_membre", id);
adp.SelectCommand = command;
adp.Fill(tabRetard);
return View(tabRetard);
}
}
This is caused by a typo in your string concatenation, it's missing whitespace between Membre.Id and WHERE:
SqlCommand command = new SqlCommand(
"SELECT Livre.titre, Membre.nom, " +
"FORMAT(Retard.DatePret, 'yyyy-MM-dd') as DatePret, Nbjour FROM Retard " +
"LEFT JOIN Livre ON Retard.Id_livre = Livre.Id " +
"LEFT JOIN Membre ON Retard.Id_membre = Membre.Id" + /*Needs a space at the end*/
/*or at the beginning*/ "WHERE Retard.Id_membre = #Id_membre", con);
Try this instead:
SqlCommand command = new SqlCommand(
"SELECT Livre.titre, Membre.nom, " +
"FORMAT(Retard.DatePret, 'yyyy-MM-dd') as DatePret, Nbjour FROM Retard " +
"LEFT JOIN Livre ON Retard.Id_livre = Livre.Id " +
"LEFT JOIN Membre ON Retard.Id_membre = Membre.Id " +
"WHERE Retard.Id_membre = #Id_membre", con);
Also, try to avoid use of AddWithValue since it can often cause problems with query parameters such as incorrect type conversion, query plan cache bloat and so on:
command.Parameters.AddWithValue("#Id_membre", id);
Prefer to use SqlCommand's Parameters.Add methods that include the SqlDbType and length parameters, e.g. for int values:
command.Parameters.Add("#Id_membre", SqlDbType.Int).Value = id;
For string values match the length of the related table/view columns, e.g.:
command.Parameters.Add("#nom", SqlDbType.NVarChar, 50).Value = nom;
Interesting reading on AddWithValue:
Can we stop using AddWithValue() already?
AddWithValue is Evil
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.
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.
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");
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 + '"