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.
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 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));
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");
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!
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 + '"