Incorrect syntax near '=' - asp.net

It gives an error when I run this code, help me to resolve this error.
Incorrect syntax near '='.
my question about what kind error is this.?
namespace SqlCommandBuilders
{
public partial class WebForm1: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection(CS);
string sqlQuery = "Select * from tblStudents where ID = "+txtStudentID.Text;
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, con);
DataSet ds = new DataSet();
da.Fill(ds, "Students");
ViewState["SQL_QUERY"] = sqlQuery;
ViewState["DATASET"] = ds;
if(ds.Tables["Students"].Rows.Count > 0)
{
DataRow dr = ds.Tables["Students"].Rows[0];
txtStudentID.Text = dr["Name"].ToString();
txtTotalMarks.Text = dr["TotalMarks"].ToString();
ddlGender.SelectedValue = dr["Gender"].ToString();
}
else
{
lblStatus.ForeColor= System.Drawing.Color.Red;
lblStatus.Text = "No Student Record with ID =" + txtStudentID.Text;
}
}
}
}

Think about the string you're creating for a moment. Suppose txtStudentID.Text is the string Joe. You'd be creating Select * from tblStudents where ID = Joe which is obviously incorrect. Joe needs quotes around it.
But, don't just put quotes around it. Here's why:
The correct thing to do is use a parameterized statement, as described on here the site linked above. Applying their example to your code, we'd get something like:
SqlCommand sqlQuery = new SqlCommand("Select * from tblStudents where ID = #username", con);
sqlQuery.Parameters.AddWithValue("#username", txtStudentID.Text);
...but I don't know what your ViewState thing is, so can't help you apply it there.

SQL commands that use text input by users should almost ALWAYS use parameterized queries to avoid SQL injection attacks and syntax errors, and it's also good to get in the habit of wrapping disposable objects (like database connections) in using statements:
DataSet ds = new DataSet();
using(SqlConnection con = new SqlConnection(CS)) {
string sqlQuery = "Select * from tblStudents where ID = #studentId";
using(SqlDataAdapter da = new SqlDataAdapter(sqlQuery, con)) {
da.SelectCommand.Parameters.Add("#studentId", SqlDbType.VarChar)
.Value = txtStudentID.Text;
da.Fill(ds, "Students");
}
}

A couple things here.
SQL parameters should always be used in cases such as this.
Also, Is Student ID a text field in the database or a number?
If its a numeric, where is the textbox being initialized? The page_load is one of the first things that happen, and since you are running this on all page_loads (even the first time), if its an empty string, it'll definitely crash regardless of whether you use parameters or not, because an empty string cannot be converted to a number.

Related

What is wrong with the following query?

I have a table containing name, surname and email. I want to retrieve them from the table and so i write:
if (LoginAs.SelectedValue == "Administrator")
{
string result;
string query = "Select * from AdminTable where ID='"+ idBox.Text +"'";
cmd1 = new SqlCommand(query, con);
result = Convert.ToString(cmd1.ExecuteScalar());
Response.Redirect("Admin.aspx");
//Admin user = new Admin(idBox.Text, "Active", mail, firstName, LastName, passwordBox.Text);
}
The problem is, it only returns the name field of the specified row even though i wrote "Select *". What is wrong here?
ExecuteScalar returns just the first column of the first row, and ignores the rest.
So you should use ExecuteReader method. An example from MSDN:
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0]));
}
}
Note that the while (reader.Read()) checks whether your query returned (more) results and positions the cursor on the next record, that you can then read. This example prints the first column's value.
The using statement makes sure the connection is closed after use, whatever happens.
Also, don't build your query directly with input from the user (such as the value of a TextBox), use parameters instead to prevent SQL injection attacks.
You must try ExecuteReader() instead of using ExecuteScalar()
ExecuteScaler is used in situation where we have to read a single value.eg:
select count(*) from tablename.
while
ExecuteReader is used for any result set with multiple rows/columns
(e.g., SELECT * from TableName)
Sample code:
string myQuery="Select * from AdminTable where ID=#myid";
SqlCommand cmd=new SqlCommand(myQuery,conn);
cmd.Parameters.AddWithValue("#myid", value);
conn.Open();
SqlDataReader dreader;
dreader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dreader.Read())
{
string Value1= dreader["COl1"].ToString();
string Value2= dreader["COl2"].ToString();
}
dreader.Close();
Always use parameterized Query
You may try cmd1.ExecuteReader() instead.

using the querystring parameter in my where clause to generate insert operation

here,using request.Querystring i find the companyname and job title of particular Job.when user logsin using username in texbix.i want the Companyname,jobtitle and username in the same row of a table.But when i generate my query it inserts the (companyName & jobtitle) in the first row and username in second row.How can i fulfill my task.Some people said,i have to keep the companyname and jobtitle in a variable...then execute.
is it a parfect solution?
if it is,how can i do that?
code:
protected void ButtonApply_Click(object sender, EventArgs e) {
String str = Request.QueryString.Get("JobNo");
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string apply = "INSERT INTO Company (CompanyName,JobTitle) select CompanyName,JobTitle from Jobs where JobNo='"+str+"'" ;
SqlCommand insertApply = new SqlCommand(apply, conn);
try {
insertApply.ExecuteScalar();
conn.Close();
Response.Redirect("ApplyJob.aspx?JobNo="+str);
}
in the apply.aspx i have following code:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string apply = "INSERT INTO Company (CandidateInformation) Values (#CandidateInformation)" ;
SqlCommand insertApply = new SqlCommand(apply, conn);
insertApply.Parameters.AddWithValue("#CandidateInformation", TextBoxaun.Text);
insertApply.ExecuteNonQuery();
conn.Close();
Response.Redirect("CompanyInfo.aspx");
Inserting two times will always result in two new rows.
You can do it all in the first insert statement:
string apply = "INSERT INTO Company (CompanyName,JobTitle, CandidateInformation) select
CompanyName,JobTitle, #CandidateInformation from Jobs where JobNo=#JobNo ;
SqlCommand insertApply = new SqlCommand(apply, conn);
insertApply.Parameters.AddWithValue("#CandidateInformation",
TextBoxaun.Text);
insertApply.Parameters.AddWithValue("#JobNo", str);
try
{
insertApply.ExecuteScalar();
conn.Close();
Response.Redirect("CompanyInfo.aspx");
}
Then you won't need the second page.
Use
Update Company Set CandidateInformation = #CandidateInformation where JobNo='"+str+"'" ;
instead of
string apply = "INSERTINTO Company (CandidateInformation) Values
(#CandidateInformation)" ;
If you will use Insert statement again, then it will always create new record in the table.
Update is used to update an already existing record of the table.

invalid column value in where clause in sql server

I have a function which would populate a datatable with the contents of a table. But its showing an annoying invalid column name error with the value I give in the WHERE clause.
public static DataTable GetRequests(string empid)
{
DataTable dt = new DataTable();
string strConnection = ConfigurationManager.AppSettings["connStr"];
using (SqlConnection connection = new SqlConnection(strConnection))
{
connection.Open();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter sAdap = new SqlDataAdapter();
sqlcmd.Connection = connection;
sqlcmd.CommandType = System.Data.CommandType.Text;
sqlcmd.CommandText = "Select * from requests Where emp_id=P001";
sAdap.SelectCommand = sqlcmd;
sAdap.Fill(dt);
}
return dt;
}
Now with this i am getting the error at
sAdap.fill
and the error is
invalid column name P001
I'm stumped at this. Any ideas why I'm facing this issue?
If it's a string constant, surround it with single quotes. 'P001' or better still, paramaratise it.
You need string delimiters around the value. Change the line to:
sqlcmd.CommandText = "Select * from requests Where emp_id='P001'";
with the single quotes around P001 and you should be fine.
You need to use single quote.
where emp_id='P001'
It looks like your P001 data is a string type. Try quoting it with single quotes before feeding it in as an sql string.
sqlcmd.CommandText = "Select * from requests Where emp_id='P001'";
If that doesn't work (though it should) you can try the like statement as in:
sqlcmd.CommandText = "Select * from requests Where emp_id like 'P001'";
You need to surround your (apparrently) text criteria with single quotes:
sqlcmd.CommandText = "Select * from requests Where emp_id = 'P001'";

System.Data.SqlClient.SqlException: Invalid column name

Trying to do a recordset, I just want one column of data, but this code is giving me an error.. I'm an ASP.NET newb, can anyone help?:
System.Data.SqlClient.SqlException: Invalid column name
'CustomerName'.
using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
{
con.Open();
using (IDataReader dr = DB.GetRS("select CustomerName from Customer where CustomerID=" + Customer.CustomerID, con))
{
string CustomerName = "CustomerName";
}
}
String EncCustomerName = Encrypt(CustomerName.Replace(".", "").Replace("-", ""),"1");
Question #2: How do I bind the database content to the CustomerName string? It seems like its only returning "CustomerName" as the value for CustomerName string.. I would like it to return the database data for CustomerName string.. Help?
Suggested to use a ExecuteScalar, so i modified the request to this
using (var con = new SqlConnection(DB.GetDBConn()))
using (var cmdContrib = new SqlCommand("SELECT CustomerName FROM Customer WHERE CustomerID=" + ThisCustomer.CustomerID, con))
{
con.Open();
string CustomerName = cmdContrib.ExecuteScalar();
}
And i Get this error:
"string CustomerName = cmdCust.ExecuteScalar();"
CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)
To answer your second question:
// Set it here so you can access it outside the scope of the using statement
string CustomerName = "";
using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
{
con.Open();
using (IDataReader dr = DB.GetRS("select CustomerName from Customer where CustomerID=" + Customer.CustomerID, con))
{
while (dr.Read())
CustomerName = dr["CustomerName"].ToString();
}
}
}
If you're sure you'll only get one CustomerName result, using a DataReader is a bit of an overkill.
SqlCommand.ExecuteScalar Example
string CustomerName = "";
using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
{
SqlCommand cmd = new SqlCommand("SELECT CustomerName FROM Customer WHERE CustomerID = " + Customer.CustomerID, con);
cmd.CommandType = CommandType.Text;
con.Open();
CustomerName = Convert.ToString(cmd.ExecuteScalar());
}
SqlCommand.ExecuteScalar Method
Additional Info
ExecuteScalar returns an object, so you'll need to convert the returned value to the proper type (in this case, string).
Also, you should declare your CustomerName value outside of the using blocks (as I did in my example) - otherwise it will be scoped to the using blocks and not available outside of them.
It means that either CustomerName or CustomerID is not a valid column within your database. Check your table again.
Make sure you are trying to connect correct database.
See CustomerName column should be in Customer table. check spelling also
First, debug and check the value of:
DB.GetDBConn()
You will verify that you are going to the same in Studio as you are in the program.
I think it is the spelling somewhere between the db and your code.
Once you get past the error, you need to fix this:
{
string CustomerName = "CustomerName";
}
You are not accessing the reader, try some kind of tutorial for that stuff.
Try doing a select * from customer where ... and put a breakpoint on your using datareader statement. Then use quick-watch on the datareader object to investigate the columns exposed in the recordset.
Or you could run the select statement on your db of choice to ensure that the column name is the same.
I agree with Madhur above, your column name is not spelled correctly. Or you are not connecting to the correct db.
Hope this helps

Why do I get a incorrect syntax exception when I am trying to connect to a SQL server?

I am trying to connect to a SQL server from a web form but getting an incorrect syntax exception in the code.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["HRMSConnectionString1"].ToString());
{
SqlCommand cmd = new SqlCommand("select * from persons where User_Id="+uid.Text+"and Password!="+pswd.Text, cn);
cn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); //exception in this line
rdr.Read();
Response.Write(rdr[0].ToString());
}
}
Please guide me where m going wrong.
The database wants to see quotes around the strings:
"select * from persons where User_Id='"+uid.Text+"'and Password!='"+pswd.Text+"'"
Try:
"Select * from persons where [User_Id] ='"+uid.Text+"'and [Password] <> '"+pswd.Text + "'"
Also: Protect your parameters! This is a must in order to prevent against SQL injection.
Looks like you are using this != operator for the purpose of Not-Equal, however that's in the progamming language. For Sql, you need to use <> operator
Also looks like you are using sql query with + which must be avoided under any cicumstances.
So your final code (in rough) should look like this
SqlCommand cmd = new SqlCommand("select * from persons where User_Id='#userid'
and Password<>'#password'",cn);
cmd.Parameters.Add(#userid,uid.Text);
cmd.Parameters.Add(#password,pswd.Text);
cn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
rdr.Read();
Response.Write(rdr[0].ToString());
(Also I am not sure what is the purpose of this query, but you are fetching * and then only using one value. If you just want to check one value, you can use query like
Select count(1) from persons where User_Id='#userid' and Password<>'#password'
and then use it with ExecuteScalar method. Just a suggestion.

Resources