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

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.

Related

Adding integer parameter to stored procedure in ASP.NET C#

While trying to pass an integer parameter #id to a stored procedure, I get an error da.Fill(ds):
Additional information: Conversion failed when converting the varchar value '#id' to data type int.
I have made sure that integer value is passed and stored procedure contain the correct datatype. What other possibilities are there to rectify this error?
SqlConnection conn = new SqlConnection(cs);
conn.Open();
SqlCommand cmd1 = new SqlCommand("asp_GetTrainingDetail", conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#id", id);
SqlDataAdapter da = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
da.Fill(ds);
If you know better, do not use AddWithValue() ... it has to "guess" what datatype you have in your DB based on what you put into the command. It is errorprone and causes unneeded conversions to take place.
Also: use using(..) around disposables, especially when using Database-access as it will close your connections even if exceptions arise - not using using might let some connection stay unclosed.
DataSet ds = new DataSet ();
using (var conn = new SqlConnection (cs))
{
using (var cmd1 = new SqlCommand ("asp_GetTrainingDetail", conn))
{
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add("#id", System.Data.SqlDbType.BigInt).Value = id;
using (var da = new SqlDataAdapter (cmd1))
{
da.Fill (ds);
}
}
}
Read the link in do not use AddWithValue() for more background infos.
Try this...
SqlConnection conn = new SqlConnection(cs);
conn.Open(); SqlCommand cmd1 = new
SqlCommand("asp_GetTrainingDetail", conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#id", Int.Parse(id));
SqlDataAdapter da = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
da.Fill(ds);

Dataset filter method

Here is my code,
Conn.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
SqlCommand sqlCmd = new SqlCommand("SELECT * from CurrentDataCR ",Conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(ds);
ds.Tables[0].DefaultView.RowFilter = " mst_remote_station_id Like'*9001*'";
Here I am getting Complete row for id 9001. I need only one column value for this id.
DataRow[] rows = ds.Tables[0].Select("mst_remote_station_id Like '%9001%'");
You can do it this way also if you need only one row just select it in the initial query.
Also you should Dispose the SqlDataAdapter after using it ! You can do it with using block
Conn.Open();
DataSet ds = new DataSet();
SqlCommand sqlCmd = new SqlCommand("SELECT * from CurrentDataCR ",Conn);
using(SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(ds);
}
ds.Tables[0].Select("mst_remote_station_id Like '%9001%'");
I don't know if the connection is global but it is bad practice to use global connection, you have connection pool so use separate connection for every query.

Declare scalar variable exception while populating DataGridview with data from SQL Server

I am trying to put data from a SQL query into a DataGridview, but when I try to run the program I am getting the exception
must declare scalar variable #cathedra
Here is the code:
string connectionString = "user id=bogdan_db; password=1234;server=localhost; Trusted_Connection=yes; database=cafedrascience; connection timeout=30";
string sql = #"select *
from researc r inner join research_cafadra rc on r.id = rc.researc_id
inner join cathedra c on c.id = rc.cafadre_id
where c.name like #Cathedra;";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#Cathedra", SqlDbType.VarChar, 50).Value = comboBox1.Text.ToString();
connection.Open();
command.ExecuteNonQuery();
SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, connectionString); //c.con is the connection string
DataTable table = new DataTable();
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
Where I am mistaking?
The problem is that you're executing the query twice (and also connecting to the database twice). Please delete command.ExecuteNonQuery() and change
SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, connectionString);
to
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
You're adding the parameter to command, which would be correct if you were actually using command. You're not... you call ExecuteNonQuery() and do nothing else with it.
You can remove these lines:
command.Parameters.Add("#Cathedra", SqlDbType.VarChar, 50).Value = comboBox1.Text.ToString();
command.ExecuteNonQuery();
And add this one after creating dataAdapter:
dataAdapter.SelectCommand.Parameters.Add("#Cathedra", SqlDbType.VarChar, 50).Value = comboBox1.Text;

Why I get Incorrect syntax near '=' error

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*.

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;

Categories

Resources