Why I get Incorrect syntax near '=' error - c#

I tried bind a label from datatable
I get this error
Incorrect syntax near '='.
at this line
da.Fill(dt);
My code : Page_Load
LbLID.Text =this.Page.Request.QueryString["DI"].ToString();
SqlConnection con = new SqlConnection("Data Source=local;Initial Catalog=DB;User
ID=sa;Password="pass);
SqlDataAdapter da = new SqlDataAdapter("select * from Table1 where ID= " +
LbLID.Text.Trim(), con);
System.Data.DataTable dt = new System.Data.DataTable();
da.Fill(dt);
lblS1.Text = dt.Rows[0][4].ToString();
lblS1.DataBind();

You can't break normal string literals across multiple lines, also your closing quote is misplaced:
SqlConnection con = new SqlConnection("Data Source=local;Initial Catalog=DB;User ID=sa;Password=pass");
Or use a verbatim literal, which you can break across multiple lines:
SqlConnection con = new SqlConnection(
#"Data Source=local;
Initial Catalog=DB;
User ID=sa;
Password=pass");
That said, your code is vulnerable to SQL injection attacks. For your own sake, and the sake of your users, you really should use parameterized queries instead of concatenating your SQL queries like that.
Here's a quick example:
using(var con = new SqlConnection(...))
{
var cmd = new SqlCommand("select * from Table1 where ID = #ID", con);
con.Open();
cmd.Parameters.AddWithValue("#ID", LbLID.Text.Trim());
var da = new SqlDataAdapter(cmd);
var dt = new DataTable();
da.Fill(dt);
lblS1.Text = dt.Rows[0][4].ToString();
lblS1.DataBind();
}
Some other tips: You should avoid using select * queries, since your database schema might change, and that would break any existing code. It would be better to select only the column you're interested in and make a simple call to ExecuteScalar.

Try this:
SqlDataAdapter da = new SqlDataAdapter("select * from Table1 where ID ='" +
LbLID.Text.Trim() + "'", con);
However note that it a very bad code which is vulnerable to sql injection.
So you should try this:
var com = new SqlCommand("SELECT * FROM Table1 WHERE ID=#id", con);
com.Parameters.AddWithValue("id",LBLID.Text.Trim());
var da = new SqlDataAdapter(com);
Or shorter:
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Table1 WHERE ID=#id", con);
da.SelectCommand.AddWithValue("id",LBLID.Text.Trim());

Its a SQL error. You aren't passing in a valid ID.
It's one of two things.
Option A: Your ID is a string. In which case.. you need to use single quotes:
SqlDataAdapter da = new SqlDataAdapter("select * from Table1 where ID= '" + LbLID.Text.Trim() + "'", con);
Option B: Your LbLId is wrong.. you're checking for ["DI"] .. when I think it should be ["ID"]:
LbLID.Text =this.Page.Request.QueryString["ID"].ToString();

I do not see any problem in the code at da.Fill(). But I see another issue at the following statement:
SqlConnection con = new SqlConnection("Data Source=local;Initial Catalog=DB;User
ID=sa;Password="pass);
...Password="pass); - rather is should be
...Password=" + pass);
OR
...Password=pass");
I am wondering you are not getting an undefined variable error for pass*.

Related

"An expression of non-boolean type specified" error executing SQL from .Net

I am getting this error:
An expression of non-boolean type specified in a context where a
condition is expected, near 'likeram'.
I entered "ram" in txt_name:
SqlConnection con = new SqlConnection(
#"Data Source=DELL_LAPTOP\sqlexpress;Integrated Security=True");
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter(
"SELECT * FROM newproj where name like" + txt_name.Text, con);
SDA.Fill(dt);
dataGridView1.DataSource = dt;
You're missing a space between the like and the string concatentation and the quotation mark around the parameter:
SqlDataAdapter SDA = new SqlDataAdapter(
string.Format("SELECT *
FROM newproj
WHERE name like '{0}'" txt_name.Text), con);
Though I'd advise you not to use that method as it is prone to SQL injections. Use SQL Parameters instead:
SqlCommand command = new SqlCommand("SELECT * FROM newproj where name like #text");
command.Parameters.AddWithValue("text", txtName.Text);
var sqlAdapter = new SqlDataAdapter(command);
You're missing ' quotes inside the string, but you shouldn't be inserting text into your SQL queries like this anyway, as they're a major SQL-injection risk:
You also need to make sure that % characters are included with the like as otherwise it will only find exact matches:
var dt = new DataTable();
using(var con = new SqlConnection(#"...")
using(var cmd = new SqlCommand(#"
select *
from newproj
where name like '%' + #text + '%'") // Add % wildcards
{
cmd.Parameters.AddWithValue("text", txtName.Text); // Safe from SQL injection
var sda = new SqlDataAdapter(command);
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
Also note that you should always dispose of your SQL command and connection objects, and that using is the best way to do this.
You missed space and single qoute in query
SqlDataAdapter SDA = new SqlDataAdapter(
"SELECT * FROM newproj where name like '" + txt_name.Text+"'", con);
you are using 'like' in where condition but you didn't added wild chars, if you want exact match records, no need of 'like' use 'name= '
like below
SqlDataAdapter SDA = new SqlDataAdapter(
"SELECT * FROM newproj where name = '" + txt_name.Text+"'", con);
if you want to search with name like use below
SqlDataAdapter SDA = new SqlDataAdapter(
"SELECT * FROM newproj where name like '%" + txt_name.Text+"%'", con);

DataAdapter.Fill(), Error arise as "Incorrect syntax near ')'"

When retrieving a datatable from database using the following code in ASP.Net & C#:
The database is located in my local machine.
string connectionString = #"Data Source=CCS90; Initial Catalog=Ribo; Trusted_Connection=True;";
SqlConnection myConn = new SqlConnection(connectionString);
myConn.Open();
SqlCommand sqlCommand = new SqlCommand("SELECT * FROM PUR_POHEADER WHERE POID = #POID", myConn);
sqlCommand.Parameters.Add("#POID", SqlDbType.Int);
sqlCommand.Parameters["#POID"].Value = Convert.ToInt32(request.ReferenceNo);
DataSet DS = new DataSet();
SqlDataAdapter AD = new SqlDataAdapter(sqlCommand, myConn);
//AD.Fill(DS);
AD.Fill(DS, "POTABLE"); //Error arise at this place
DataTable DT = DS.Tables[0];
myConn.Close();
When compiler comes to the line AD.Fill(DS, "POTABLE");, error occurs at Incorrect syntax near '). What may be the reason?
You create a SqlCommand with a SELECT statement and then you don't use it. What is insertStatement? Surely you should be using sqlCommand.
You may try with
AD.Fill(DS);
instead of
AD.Fill(DS,"PORTABLE");
Also try:
SqlDataAdapter AD = new SqlDataAdapter(sqlCommand);
instead of
SqlDataAdapter AD = new SqlDataAdapter(insertStatement, myConn);
Problem is here:
SqlDataAdapter AD = new SqlDataAdapter(insertStatement, myConn);
replace it with:
SqlDataAdapter AD = new SqlDataAdapter(sqlCommand);
and also you are using this overload i think:
AD.Fill(DS, "NameOfDataTable");
then you can access it like this:
DataTable DT = DS.Tables["NameOfDataTable"];
insetad of using 0 index.

Unable to execute query - Error: Incorrect syntax near 'Media'

This code is showing an error:
Incorrect syntax near 'Media'.
What does it mean? Where am I making a mistake?
if (!IsPostBack)
{
if (Request.QueryString["sub"] != null)
{
SqlDataAdapter da = new SqlDataAdapter(
"select * from entry_table Where sub=" + Request.QueryString["sub"],
ConfigurationManager.ConnectionStrings["cozmotestConnectionString"].ConnectionString);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Label1.Text = dt.Rows[0]["sub"].ToString();
Label2.Text = dt.Rows[0]["body"].ToString();
}
}
}
<div style=" padding-bottom:10px"><h1><asp:Label Font-Bold="true" ID="Label1" runat="server" Text="Label"></asp:Label></h1></div>
<div><asp:Label ID="Label2" runat="server" Text="Label"></asp:Label></div>
Since you tagged nvarchar with your question, I assume your sub column is nvarchar.
That's why you need to use single quotes with it's values. Like;
..sub = '" + Request.QueryString["sub"] + "'"..
But don't use this way.
Much more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Use using statement to dispose your SqlConnection, SqlCommand and SqlDataAdapter as well.
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cozmotestConnectionString"].ConnectionString))
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "select * from entry_table Where sub = #sub";
cmd.Parameters.Add("#sub", SqlDbType.NVarChar).Value = Request.QueryString["sub"];
using(SqlDataAdapter da = new SqlDataAdapter(cmd, con))
{
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Label1.Text = dt.Rows[0]["sub"].ToString();
Label2.Text = dt.Rows[0]["body"].ToString();
}
}
}
You probably need single quotes around your value in your where clause.
SqlDataAdapter da = new SqlDataAdapter("select * from entry_table Where sub='" + Request.QueryString["sub"] + "'", ConfigurationManager.ConnectionStrings["cozmotestConnectionString"].ConnectionString);
Although, I would highly recommend that you use a parametrized query to avoid SQL injection attacks
Do something like this, it may help you on this issue,
string str = Request.QueryString["sub"];
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cozmotestConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter(
"select * from entry_table Where sub='"+str+"'",con)
//Your remaining parts will come here
Please let me know the result.

How use WHERE in SqlDataAdapter in C#

How use WHERE in SqlDataAdapter in C#?
I want get name in a textbox and use that at query but it wont work .
SqlConnection sqlconnection = new SqlConnection("Server=Behnam\\Accounting;Initial Catalog=Accounting;Integrated Security=TRUE");
DataTable dt = new DataTable();
string _search_name = txt_search.Text;
SqlDataAdapter SDA = new SqlDataAdapter("SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 FROM tbl_user WHERE dbo.tbl_user.name=_search_name ", sqlconnection);
SDA.Fill(dt);
dataGridView1.DataSource = dt;
Prepare the command text and use a parameter for the value of your search.
Then use that command text to initialize a new SqlCommand. Fill the parameter value with AddWithValue and pass the SqlCommand to the constructor of the SqlDataAdapter.
string cmdText = "SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 " +
"FROM tbl_user WHERE dbo.tbl_user.name=#search_name"
SqlCommand cmd = new SqlCommand(cmdText, sqlconnection);
cmd.Parameters.AddWithValue("#search_name", _search_name);
SqlDataAdapter SDA = new SqlDataAdapter(cmd);
The SqlDataAdapter will store your command as the SelectCommand property and will use the passed in SqlCommand to execute the query to retrieve the records from the database.
Keep in mind that AddWithValue is a shortcut with some drawbacks. For example it pass Always a string as a nvarchar parameter with size equal to the actual lenght of the variable. This effectively reduces the performance of the Sql Server Optimizer.
This is a very enlightening article on the issue
So, you were pretty close, you just needed to define a parameter inside the query and then add that parameter. However, in the following code block I've also conveniently recommended a more appropriate approach to using the classes needed to get the data (pun intended). The using statement here ensures that the objects get disposed of properly after you are done using them (man I just can't stop with the puns!)
using (SqlConnection c = new SqlConnection(connString))
{
c.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(
"SELECT dbo.tbl_user.field1, dbo.tbl_user.field2 FROM tbl_user " +
"WHERE dbo.tbl_user.name= #name", c))
{
sda.SelectCommand.Parameters.AddWithValue("#name", txt_search.Text);
DataTable dt = new DataTable();
sda.Fill(dt);
}
}
Try this.
you were using the string directly in the query which will go undetected.
SqlConnection sqlconnection = new SqlConnection("Server=Behnam\\Accounting;
Initial Catalog=Accounting;Integrated Security=TRUE");
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 FROM tbl_user WHERE dbo.tbl_user.name=#searchName" , sqlconnection);
SDA.SelectCommand.Parameters.AddWithValue("#searchName", txt_search.Text);
SDA.Fill(dt);
dataGridView1.DataSource = dt;

an SQL Search query using more than one condition

my problem is that , i made a child form for searching , but i have problem in sql query and parameters , my code is
SqlConnection sc = new SqlConnection(
"Data Source=MOHAMMED-PC;Initial Catalog=salessystem;Integrated Security=True");
SqlCommand command = new SqlCommand(
"Select * from customers WHERE (docno = #doc) OR (NAME LIKE #name ) OR (salepoint = #salepoint)", sc);
DataTable dt = new DataTable();
command.Parameters.AddWithValue("#doc", doctxt.Text);
command.Parameters.Addwithvalue("#name", nametxt.Text);
command.Parameters.AddWithValue("#salepoint", salepointtxt.Text);
SqlDataAdapter sda = new SqlDataAdapter(command, sc);
sda.Fill(dt);
dataGridView1.DataSource = dt;
i have error in sql adapter command and in where clause command , any help ??
Three things:
You have a typo on this line
command.Parameters.Addwithvalue("#name", nametxt.Text);
The method is AddWithValue (note the case difference)
The constructor of SqlDataAdapter takes the command but no connection then since the command already contains the connection, so this is correct:
SqlDataAdapter sda = new SqlDataAdapter(command);
Probably the most important last:
If you use LIKE you need to use the wild-cards %:
command.Parameters.AddWithValue("#name", string.Format("%{0}%",nametxt.Text);

Categories

Resources