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);
Related
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.
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#?
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;
Hello guys I have got this code:
SqlCommand scom = new SqlCommand(
"INSERT INTO klient(name,surname)
values(#kname,#ksurname)",
conn);
scom.Parameters.AddWithValue("#kname", kname.Text);
scom.Parameters.AddWithValue("#ksurname", ksurname.Text);
conn.Open();
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM klient", spojeni);
SDA.Fill(dt);
conn.Close();
It should insert data from textboxes: kname, ksurname, but it closes the form without showing them in MS SQL table klient
Missing the ExecuteNonQuery call
SqlCommand prikaz = new SqlCommand("INSERT INTO klient(name,surname) values(#kname,#ksurname)", spojeni);
prikaz.Parameters.AddWithValue("#kname", kname.Text);
prikaz.Parameters.AddWithValue("#ksurname", ksurname.Text);
spojeni.Open();
prikaz.ExecuteNonQuery();
......
A command should be executed to update the database...
You haven't executed the command.
prikaz.ExecuteNonQuery();
The above stated problem is due to the missing executenonquery() statement, add this statement in your code
spojeni.Open();
prikaz.ExecuteNonQuery();
i found using of prepared statements in PHP by mysqli_stmt_prepare() Function.
what is like it in C# for SQL-Server?
i found this code example(using parameterize command). is this what i am looking for?
SqlConnection conn = new SqlConnection();
SqlCommand com = new SqlCommand();
SqlDataAdapter dap = new SqlDataAdapter();
DataTable tbl = new DataTable();
SqlParameter param = new SqlParameter();
conn.ConnectionString = #"Data Source=...";
com.Connection = conn;
com.CommandText = "select * from tbl1 where id<#id";
com.Parameters.AddWithValue("#id",4);
com.CommandType = CommandType.Text;
dap.SelectCommand = com;
conn.Open();
dap.Fill(tbl);
conn.Close();
dataGridView1.DataSource = tbl;
if NO, then what?
if YES, tell me how to using character '?' instead of writing #id in command text.
thanks
SQL Server (at least, via SqlClient) uses named parameters. That code will indeed execute a parameterised query, but a few notes:
it hasn't been formally "prepared" (see .Prepare()), but you pretty much never need to anyway
several of those objects are IDisposable; you should have usings for them
DataTable (and adapter, etc) will work, but is in decline (with mapped classes being preferred, IMO)
seeing a DataGridView and a SqlCommand in the same method probably means your UI code is too close to the data access code; I would push the data-access stuff down a level, personally
For example:
DataTable tbl = new DataTable();
using(var conn = new SqlConnection(#"Data Source=..."))
using(var com = conn.CreateCommand())
{
com.CommandText = "select * from tbl1 where id<#id";
com.Parameters.AddWithValue("#id",4);
com.CommandType = CommandType.Text;
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = com;
conn.Open();
dap.Fill(tbl);
conn.Close();
}
return tbl;
(and bind it to the DataGridView back at the UI)
Of course, if the parameter value is always 4 you could code that into the TSQL directly.
Yes, but it is no way to use '?' mark.