How can I use a Session string in a SQL command? - c#

I'm trying to use a session string variable as a WHERE clause condition in a SQL command, code below in C#
static string strConn = ConfigurationManager.ConnectionStrings["pEAnUtWoRM"].ToString();
SqlConnection conn = new SqlConnection(strConn);
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
displayProfiles();
}
}
private void displayProfiles()
{
if (Session["email"] != null )
{
string email = Convert.ToString(Session["email"]);
SqlCommand cmd = new SqlCommand("SELECT Student.Name FROM Student " +
"LEFT JOIN Mentor ON Student.MentorID = Mentor.MentorID " +
"WHERE Mentor.EmailAddr = " + email.ToString(), conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet result = new DataSet();
conn.Open();
da.Fill(result, "StudentProfile");
conn.Close();
gvProfileList.DataSource = result.Tables["StudentProfile"];
gvProfileList.DataBind();
}
}
Connection strings and SqlConnection work fine (it's not in the method) as I've tested it out on other aspx pages. Error says:
System.Data.SqlClient.SqlException: The multi-part identifier could not be bound on da.Fill(result, "StudentProfile");

The exception is thrown because the query syntax is incorrect since the value of email.ToString() is not appropriately escaped, resulting in a query such as the following one:
SELECT
Student.Name
FROM
Student
LEFT JOIN
Mentor ON Student.MentorID = Mentor.MentorID
WHERE
Mentor.EmailAddr = email#outlook.com
My assumption is that your intent was to produce the following query, where the value of email.ToString() (e.g. email#outlook.com) is between single quotes:
SELECT
Student.Name
FROM
Student
LEFT JOIN
Mentor ON Student.MentorID = Mentor.MentorID
WHERE
Mentor.EmailAddr = 'email#outlook.com'
A possible fix would be adding a parameter (e.g. #EmailAddress) to the SQL command and assigning the email value to it as follows:
const string EMAIL_ADDRESS_PARAMETER_NAME = "#EmailAddress";
SqlCommand cmd = new SqlCommand("SELECT Student.Name FROM Student " +
"LEFT JOIN Mentor ON Student.MentorID = Mentor.MentorID " +
$"WHERE Mentor.EmailAddr={EMAIL_ADDRESS_PARAMETER_NAME}", conn);
cmd.Parameters.Add(EMAIL_ADDRESS_PARAMETER_NAME, SqlDbType.VarChar).Value = email;

Related

System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.' on Datatable and object

I've looked at a lot of similar questions on this site and elsewhere but none of them have helped me.
I'm trying to make a database connection with a query but I get the error
System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.'
on 2 different lines of code. I've tried to use spaces in the query around the = but that doesn't help.
Code 1 is:
string connectieString = dbConnection();
SqlConnection connection = new SqlConnection(connectieString);
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#attackCategory", SqlDbType.NChar).Value = attackCategory;
select.Parameters.Add("#taughtOn", SqlDbType.NVarChar).Value = taughtOn;
select.CommandText = "SELECT ID, Name FROM attackCategory = #attackCategory WHERE TaughtOn = #taughtOn";
using (SqlDataAdapter sda = new SqlDataAdapter(select.CommandText, connection))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
The exception is thrown on the sda.Fill(dt); line of code. This code works if no parameters are used in the query:
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn ='" + taughtOn + "'";
And code 2 is:
string connectieString = dbConnection();
SqlConnection connection = new SqlConnection(connectieString);
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#attackCategory", SqlDbType.NVarChar).Value = attackCategory;
select.Parameters.Add("#ID", SqlDbType.Int).Value = id;
select.CommandText = "SELECT Name FROM attackCategory = #attackCategory WHERE ID = #ID";
connection.Open();
object name = select.ExecuteScalar();
connection.Close();
return name;
The exception fires on the object name = select.ExecuteScalar(); line of code. This code works if 1 parameter is used in the query:
select.Parameters.Add("#ID", SqlDbType.Int).Value = id;
select.CommandText = "SELECT Inhabitants FROM Planet WHERE ID=#ID";
You cannot provide table name has parameter, parameter applies in where clause with columns value.
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn ='" + taughtOn + "'";
but, we need to simplify to use parameter in this query.
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#taughtOn", SqlDbType.VarChar,50).Value = taughtOn;
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn =#taughtOn";
select.CommandText = cmd;
In the above tsql query, string concatenation applies and table name is included in the string, which will work.
Edit:-
I get it why you the sqlDataAdapter is not Recognizing the parameter.
Reason is you have not provided it. Yes, That's right you have provided the CommandText and not the Command Object which is of select variable.
I have corrected your code.
select.Parameters.Add("#taughtOn", SqlDbType.VarChar, 50).Value = taughtOn;
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn =#taughtOn";
select.CommandText = cmd;
select.Connection = new SqlConnection("provide your sql string");
using (SqlDataAdapter sda = new SqlDataAdapter(select))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Hope this helps !!
You can't bind object names like that. For object names, you'll have to resort to some sort of string concatenation. E.g.:
select.Parameters.Add("#taughtOn", SqlDbType.NVarChar).Value = taughtOn;
select.CommandText = "SELECT ID, Name FROM " + attackCategory + " WHERE TaughtOn=#taughtOn";
Note:
This is an over-simplified solution that does nothing to mitigate the risk of SQL-Injection attacks. You'll need to sanitize attackCategory before using it like this.

How to show SQL query result in a Textbox?

I have the following code:
dbConnection cn = new dbConnection();
SqlCommand cmd = new SqlCommand();
protected void dropdown_student_SelectedIndexChanged(object sender, EventArgs e)
{
string StudentGUID = dropdown_student.SelectedValue;
cn.con.Open();
cn.cmd.Connection = cn.con;
cn.cmd.CommandText = "select SUM(Marks) AS 'Total' from Marksheet where StudentGUID = " + StudentGUID + " ";
dr = cn.cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
textbox_total.Text = dr["Total"].ToString();
}
cn.con.Close();
}
}
I want to show the total marks value in the textbox but it does not work. Can anyone point me in the right direction?
Try something like this:
// define your query upfront - using a PARAMETER!
string query = "SELECT SUM(Marks) FROM dbo.Marksheet WHERE StudentGUID = #StudentID;";
// put the SqlConnection and SqlCommand into using blocks
using (dbConnection cn = new dbConnection())
using (SqlCommand cmd = new SqlCommand(query, cn))
{
// define the parameter value
cmd.Parameters.Add("#StudentID", SqlDbType.UniqueIdentifier).Value = dropdown_student.SelectedValue;
cn.Open();
// use ExecuteScalar if you fetch one row, one column exactly
object result = cmd.ExecuteScalar();
cn.Close();
if(result != null)
{
int value = (int)result;
textbox_total.Text = value.ToString();
}
}
You SQL query is wrong. Try like below:
string query = string.Format("SELECT SUM(Marks) FROM dbo.Marksheet WHERE StudentGUID = '{0}';", StudentID);
Always try to follow this kind of standard practice and you will never fail.
Try putting single Quote around the GUID variable in SQL query.
cn.cmd.CommandText = "select SUM(Marks) AS 'Total' from Marksheet where StudentGUID = '" + StudentGUID + " '";

System.Data.SqlClient.SqlException: Incorrect syntax near ')'

I am getting an error in my SQL command with which I am trying to retrieve values from a SQL Server database. It is showing a error in browser as mentioned in title. If I remove the brackets it shows error in AND operator
string jdate = (string)Session["jdate"];
string clas = (string)Session["class"];
string scode = (string)Session["scode"];
string dcode = (string)Session["dcode"];
cn = new SqlConnection(ConfigurationManager.ConnectionStrings["dummyConnectionString"].ToString());
// error shows up on this line
string slct = "SELECT Route.Route_Source, Route.Route_Destination, Flight.Flight_Name, Schedule.Depart_Time, Schedule.Arr_Time, Schedule.Route_rate_Ad , Seats." + jdate +
"Schedule.Sch_id FROM Schedule INNER JOIN Flight ON Schedule.Flight_Id = Flight.Flight_id INNER JOIN Route ON Schedule.Route_id = Route.Route_id INNER JOIN Seats ON Seats.Sch_id = Schedule.Sch_id WHERE (Route.Route_Source =" + scode + ") AND (Route.Route_Destination =" + dcode + ") AND (Seats.Class=" + clas + ") ORDER BY Schedule.Depart_Time, Schedule.Arr_Time, Flight.Flight_Name";
cn.Open();
SqlDataAdapter da = new SqlDataAdapter(slct, cn);
DataSet ds = new DataSet();
da.Fill(ds);
SearchView.DataSource = ds;
SearchView.DataBind();
You should use a parameterized query.
This would allow a more understandable query text, avoid simple syntax errors
(like the missing comma at the end of the first line (jdate)),
avoid Sql Injections and parsing problems with strings containing quotes or decimal separators
string slct = #"SELECT Route.Route_Source, Route.Route_Destination,
Flight.Flight_Name, Schedule.Depart_Time, Schedule.Arr_Time,
Schedule.Route_rate_Ad, Seats." + jdate + ", Schedule.Sch_id " +
#"FROM Schedule INNER JOIN Flight ON Schedule.Flight_Id = Flight.Flight_id
INNER JOIN Route ON Schedule.Route_id = Route.Route_id
INNER JOIN Seats ON Seats.Sch_id = Schedule.Sch_id
WHERE (Route.Route_Source = #scode)
AND (Route.Route_Destination =#dcode)
AND (Seats.Class=#class)
ORDER BY Schedule.Depart_Time, Schedule.Arr_Time, Flight.Flight_Name";
cn.Open();
SqlCommand cmd = new SqlCommand(slct, cn);
cmd.Parameters.AddWithValue("#scode", scode);
cmd.Parameters.AddWithValue("#dcode", dcode);
cmd.Parameters.AddWithValue("#class", clas);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);

i need to get more than one value from database sql

I need to get 6 values from database and bind them to link button texts her is the code
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//string post = Request.QueryString["post"];
////string title = "nokia";
string date = DateTime.Now.ToShortDateString();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\nokiaoaq\Desktop\WebSite1\App_Data\Database.mdf;Integrated Security=True;User Instance=True";
try
{
conn.Open();
//string str = "insert into Table1 (title , date_ ,www, cat) values (' " + TextBox1.Text + "','" + DateTime.Now.ToShortDateString() + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Text + "')";
////string str = "INSERT INTO Table1 (title,date_,www ) values ('ddddddd','aaaaaaa','qqqqqq')";
string str =
//"SELECT from table1 WHERE cat = 1 and datee='" + date + "'ORDER BY datee";
"SELECT table1.title FROM table1 WHERE cat = 1 and datee='" + date + "'ORDER BY datee DESC";
SqlCommand objcmd = new SqlCommand(str, conn);
SqlDataAdapter da1 = new SqlDataAdapter(objcmd);
DataTable dt = new DataTable();
da1.Fill(dt);
//DataRow dr = new DataRow();
//DataRow dr = ds.Tables[0].Rows[0];
foreach (DataRow dr in dt.Rows)
{
ml1.Text = dr[0].ToString();
ml2.Text = dr[1].ToString();
ml3.Text = dr[2].ToString();
ml4.Text = dr[3].ToString();
ml5.Text = dr[4].ToString();
ml6.Text = dr[5].ToString();
}
}
catch (Exception ex)
{
Label4.Text = "Failed to connect to data source";
}
finally
{
conn.Close();
}
}
}
ml is link button id
You are trying to assign 6 fields from the row returned to 6 different textboxes, but your select query asks for just one field. If you want more than one field returned then add their names to the select query (change fieldX to the appropriate field name).
string str = "SELECT title, field1, field2, field3, field4, field5 " +
"FROM table1 WHERE cat = 1 and datee=#dt ORDER BY datee DESC";
also do not use string concatenation to build the sql statement. Use always a parametrized query
SqlCommand objcmd = new SqlCommand(str, conn);
objcmd.Parameters.AddWithValue("#dt", datee);
.....
this will avoid problem with formatting strings, date, numbers etc, but also the sql injection problem.
By the way, I hope that your code returns just one row because, as it stands now, if you have more than one row returned then only the one with the earliest date will be shown in the textboxes. (And if this is the case then the order by is useless). If you have more than one row returned then you should consider to bind the datatable to a GridView to show all records returned.

An expression of non-boolean type specified in a context where a condition is expected, near 'ID'

can someone point out what is causing this error? I've been trying to fix it but I failed. I don't understand what is wrong with the 'ID' ... which part exactly that generated this error?
Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = SqlDataSource1.ConnectionString;
string str = "SELECT * FROM Student "
+ " WHERE Student ID = '" + StudentID.Text + "' AND "
+ " Password = '" + SPassword.Text + "'";
SqlCommand cmdSelect = new SqlCommand(str, conn);
SqlDataReader reader;
conn.Open();
reader = cmdSelect.ExecuteReader();
if (reader.Read())
{
if (StudentID.Text == "900000000")
Response.Write("<body onload=\"window.open('Admin.aspx', '_top')\"></body>");
else
Response.Write("<body onload=\"window.open('user.aspx', '_top')\"></body>");
}
else
lblMsg.Text = "Invalid Username and/or Password, please re-try!!";
conn.Close();
}
SELECT * FROM Student WHERE Student.ID ... (you have a space instead of a dot)
You could omit the Student entirely and just use ID (like you have for Password).

Categories