I want to perform a simple search using the SQL LIKE function. Unfortunately for some reason , it doesn't seem to be working. Below is my code.
private void gvbind()
{
connection.Open();
string sql = "";
if (txtSearch.Text.Trim() == "")
{
sql = "SELECT a.cname,[bid],b.[bname],b.[baddress],b.[bcity],b.[bstate],b.[bpostcode],b.[bphone],b.[bfax],b.[bemail] FROM [CLIENT] a INNER JOIN [BRANCH] b ON a.clientID=b.clientID ORDER BY a.[clientID]";
}
else
{
sql = "SELECT a.cname,[bid],b.[bname],b.[baddress],b.[bcity],b.[bstate],b.[bpostcode],b.[bphone],b.[bfax],b.[bemail] FROM [CLIENT] a INNER JOIN [BRANCH] b ON a.clientID=b.clientID WHERE b.[bname] LIKE '%#search%' ORDER BY a.[clientID]";
}
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.Parameters.AddWithValue("#search", txtSearch.Text.Trim());
cmd.CommandType = CommandType.Text;
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd;
DataSet ds = new DataSet();
adp.Fill(ds);
connection.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gvBranch.Enabled = true;
gvBranch.DataSource = ds;
gvBranch.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvBranch.DataSource = ds;
gvBranch.DataBind();
int columncount = gvBranch.Rows[0].Cells.Count;
gvBranch.Rows[0].Cells.Clear();
gvBranch.Rows[0].Cells.Add(new TableCell());
gvBranch.Rows[0].Cells[0].ColumnSpan = columncount;
gvBranch.Rows[0].Cells[0].Text = "No Records Found";
}
ds.Dispose();
}
the above method is called in the Page_Load() method using
if((!Page.IsPostBack))
{
gvBind();
}
it is called on button search click aslo. However, it return No record found when ever i perform the search.
Use
LIKE '%' + #search + '%'
instead of
LIKE '%#search%'
Full query;
...
else
{
sql = "SELECT a.cname,[bid],b.[bname],b.[baddress],b.[bcity],b.[bstate],b.[bpostcode],b.[bphone],b.[bfax],b.[bemail] FROM [CLIENT] a INNER JOIN [BRANCH] b ON a.clientID=b.clientID WHERE b.[bname] LIKE '%' + #search + '%' ORDER BY a.[clientID]";
}
And actually, you don't need to use square brackets ([]) every column in your query. Use them if your identifiers or object names are a reserved keyword.
Thanks. It works , but any explanation for that?
The main problem is here, your query parameter is inside quotes. In quotes, SQL Server will recognize it as a string literal and never sees it as a parameter.
Related
I am using C# to create a windows form.
I am trying to set a condition statement for a particular value that is retrieved from my database by the onclick of a button. The datatype of the column is 'integer'.
Below is my code:
string checkquantity = "SELECT `inventory_item`.`Item_Quantity_Available`FROM `inventory_item` , `patient`, `out_treatment`WHERE `inventory_item`.`Item_ID` = `out_treatment`.`Inventory_ID`AND `patient`.`Patient_ID` = `out_treatment`.`Patient_ID`AND `out_treatment`.`Patient_ID`= '" + pid + "' ";
MySqlCommand selectout = new MySqlCommand(checkquantity, connect);
MySqlDataAdapter selectdata = new MySqlDataAdapter(checkquantity, connect);
DataTable selecttable = new DataTable();
selectdata.Fill(selecttable);
DataSet ds = new DataSet();
selectdata.Fill(selecttable);
selectdata.Fill(ds);
int i = ds.Tables[0].Rows.Count;
if ( i <= 0)
{
MessageBox.Show("Out of Stock");
}
I'm new with c#.
I don't think the int i = ds.Tables[0].Rows.Count; is the right way.
Any help is much appreciated.
First of all, like #Flydog57 said, you should not concatenate your sql query. The best way is to use parameters, for example:
string checkquantity = "SELECT i.Item_Quantity_Available " +
" FROM inventory_item i JOIN out_treatment t ON i.Item_Id = t.Inventory_ID " +
" JOIN patient p ON t.Patient_ID = p.PatiendID " +
" WHERE t.Patient_ID = #Patiend_ID";
MySqlCommand selectout = new MySqlCommand(checkquantity, connect);
// set the parameter value
selectout.Parameters.AddWithValue("#Patiend_ID", patient_id_value);
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
{
if ((int)rdr["Item_Quantity_Available"] == 0)
MessageBox.Show("Out of Stock");
}
In second place, you could use a MySqlDataReader to verify that Item_Quantity_Available is equal to 0, like in the previous example. Otherwise, If you just wants to verify if there is data, the condition could be something like that:
if (!rdr.Read())
{
MessageBox.Show("Out of Stock");
}
The third improvemente is to join tables with the join clause.
I have two columns with date_of_delivery and date_of_receipt. I want to filter my data
private void button25_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
if(radioButton9.Checked)
{
if ((Convert.ToDateTime(dateTimePicker3.Value)) <= (Convert.ToDateTime(dateTimePicker4.Value)))
{
try
{
string query = "SELECT work_id, surname, first_name, patronymic, type_of_service.name_type_of_service, date_of_receipt, date_of_delivery, car_model.name_model, price_for_work FROM mechanic INNER JOIN work ON work.mechanic_id = mechanic.mechanic_id INNER JOIN type_of_service ON work.type_of_service_id = type_of_service.type_of_service_id INNER JOIN car ON work.car_id = car.car_id INNER JOIN car_model ON car.car_model_id = car_model.car_model_id WHERE work.date_of_receipt >= '" + Convert.ToDateTime(dateTimePicker3.Value) + "' AND work.date_of_delivery <= '" + Convert.ToDateTime(dateTimePicker4.Value) + "'";
MessageBox.Show("" + query);
dataGridView2.DataSource = query;
SqlDataAdapter da = new SqlDataAdapter(query, SqlConn);
da.Fill(ds, query);
dataGridView2.DataSource = ds.Tables[query];
}
catch (Exception e2)
{
MessageBox.Show(e2.Message);
}
}
else
{
MessageBox.Show("Дата начала ремонта не может быть позже его завершения ");
}
}
else if(radioButton10.Checked)
{
string query = "SELECT work_id, surname, first_name, patronymic, type_of_service.name_type_of_service, date_of_receipt, date_of_delivery, car_model.name_model, price_for_work FROM mechanic INNER JOIN work ON work.mechanic_id = mechanic.mechanic_id INNER JOIN type_of_service ON work.type_of_service_id = type_of_service.type_of_service_id INNER JOIN car ON work.car_id = car.car_id INNER JOIN car_model ON car.car_model_id = car_model.car_model_id WHERE work.price_for_work BETWEEN " + Convert.ToInt32(textBox16.Text) + " AND " + Convert.ToInt32(textBox17.Text) + "";
MessageBox.Show("" + query);
dataGridView2.DataSource = query;
SqlDataAdapter da = new SqlDataAdapter(query, SqlConn);
da.Fill(ds, query);
dataGridView2.DataSource = ds.Tables[query];
}
}
However, the data is not sorted. Because the database format of the date 01.02.2015 . How to make sure everything works
As I wrote in the comments, date types does not have a format.
You are sending a string that represents a date value to the database, (the default .ToString() of the DateTime object is called since there is an implicit conversion from date to string when you are concatenating the DateTime to the sql string).
When using strings for a date value in sql it's best to use ANSI-SQL format which is yyyy-MM-dd. This format guarantees that SQL Server will interpret the string as a proper date.
However, concatenating strings to create an SQL statement is a security hazard, since it's an opening for SQL injection attacks.
The proper way is to use parameterized queries or stored procedures.
Replace your query's where clause from this
WHERE work.date_of_receipt >= '" + Convert.ToDateTime(dateTimePicker3.Value) +
"' AND work.date_of_delivery <= '" + Convert.ToDateTime(dateTimePicker4.Value) + "'"
to this:
WHERE work.date_of_receipt >= #date_of_receipt
AND work.date_of_delivery <= #date_of_delivery
Then use the SqlDataAdapter's SelectCommand's Parameters collection to add the values for the parameters:
SqlDataAdapter da = new SqlDataAdapter(query, SqlConn);
da.SelectCommand.Parameters.Add("#date_of_receipt ", SqlDbType.Date).Value = dateTimePicker3.Value;
da.SelectCommand.Parameters.Add("#date_of_delivery", SqlDbType.Date).Value = dateTimePicker4.Value;
(Note that the add command returns a reference to the SqlParameter you've just added, therefor you can write the .Value to specify the value of the parameter when adding it to the SelectCommand.
Note that the value of the DateTimePicker is already a DateTime type, so there is no need to use Convert.ToDateTime when adding it.
Do the same thing with all other queries (of course, don't forget to use the proper data types for the parameters).
System.DateTime dt16 = System.DateTime.Parse(textBox16.Text);
string sTextBox16 = dt16.ToString("dd.MM.yyyy");
System.DateTime dt17 = System.DateTime.Parse(textBox17.Text);
string sTextBox17 = dt17.ToString("dd.MM.yyyy");
string query = "SELECT Required Columns WHERE work.date_of_receipt >= "+sTextBox16 +"' AND work.date_of_delivery <= '" + sTextBox17 +"'";
I have a method which takes a single string parameter (ID).
I want to use SqlCommand to return a DataTable of results from a query. I'm trying to call a table function from my database (Sql Server) in the query and pass in my ID parameter. The contents of this DataTable will then populate a Combobox. Here's what I have so far...
public string populateCompanyTransSellingEntityLookUp(string BlockId)
{
string _sql = "";
SqlCommand _comm = new SqlCommand();
_comm.Parameters.AddWithValue("(#block_id", BlockId);
_comm.CommandText = "SELECT [name] FROM dbo.fnGetBlockCompanyWIList(#block_id) ORDER BY [name]; ";
_comm.Connection = _conn;
_comm.CommandTimeout = _command_timeout;
DataTable dt = new DataTable();
try
{
SqlDataReader myReader = _comm.ExecuteReader();
dt.Load(myReader);
}
catch (Exception)
{
throw;
}
Combo.DataSource = dt;
return _sql;
}
But i'm getting a error, "Must declare scalar variable '#block_id'". why?
You have an extra bracket here, you should remove it:
_comm.Parameters.AddWithValue("(#block_id", BlockId);
^^^
And perhaps it doesn't matter but give value to your parameter after you set the CommandText:
_comm.CommandText = "SELECT [name] FROM dbo.fnGetBlockCompanyWIList(#block_id) ORDER BY [name]; ";
_comm.Parameters.AddWithValue("#block_id", BlockId);
my question is very simple:
i have a SQL Table with a column name 'lastname' with fields lastname1,lastname2,lastname3...
In my c# code, i have a method that inserts in the table a row only if the field of the column lastname is not present in the table. This method in input has lastname, so for my INSERT is a parameter.
How can i compare and conseguently check if the field lastname is already in table?
Thanks
You should always use unique constraints in the table if a field must be unique. On that way you prevent duplicates always, even if the input was directly from SSMS or another application.
Then the easiest would be to handle the sql-exception that is raised according to it's number.
....
try
{
int inserted = cmd.ExecuteNonQuery();
} catch (SqlException ex)
{
if (ex.Number == 2601)
{
// show meaningful error message
MessageBox.Show("Cannot insert duplicate key row in object");
}
else
throw;
}
....
This SQL will insert a new record only if the value isn't already in the table:
INSERT INTO Your_Table ( LastName )
SELECT #NewLastName
WHERE NOT EXISTS( SELECT * FROM Your_Table WHERE LastName = #NewLastName )
There are two option one is from sql side another way is from code behind.
unfortunately you can't change your sql code i agree with #David.
from code behind you have to do something like this.
First you have to select all the data from your table and check that data. something like this.
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con; //Your connection string"
cmd.CommandText = "Select * from table1"; // your query
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = new DataTable();
dt = ds.Tables[0];
int count=0;
for (int i = 0; i > dt.Rows.Count; i++)
{
if (Convert.ToString(dt.Rows[i]["LastName"]) == Lastname)
{
count++;
}
}
if (count > 0)
{
//insert code for data
}
else
{
var script = "alert('"+ Lastname + "already exist.');";
ClientScript.RegisterStartupScript(typeof(Page), "Alert", script, true);
// or you can use here your Update statement
}
May this will help you and you can understand.
here i have tried to select a data from db make use of like statement, but it has search with the 1st digit of my data. but i need to write the code, like search instead of first 3 digit of my data. can any one help me.
public void CC()
{
CCddl.Items.Clear();
ListItem l = new ListItem();
l.Text = "-Select-";
CCddl.Items.Add(l);
CCddl.SelectedIndex = 0;
con.Open();
SqlCommand cmd = new SqlCommand("select Componetcode from dbo.tbl_component where Sitecode like '%" + TextBox1.Text + "%'", con);
SqlDataReader dr1;
dr1 = cmd.ExecuteReader();
while (dr1.Read())
{
ListItem n = new ListItem();
n.Text = dr1["Componetcode"].ToString().Trim();
CCddl.Items.Add(n);
}
dr1.Close();
con.Close();
}
you cannot operate the like on number you need to convert number to stirng by using cast or convert ...
EDIT
you can also make use of substring function to skip frist three char or your data in column
select * from (
select column1,cast(column2 as varchar(30)) as column2 from tablename
) d where
substring(column2,4, LEN(column2) - 3 ) like '%textosearch%'
you need to write down
select * from tablename where column like '___textosearch%'
so your code will be
SqlCommand cmd = new SqlCommand("select Componetcode from dbo.tbl_component
where Sitecode like '___" + TextBox1.Text + "%'", con);
_ allows you to match on a single character in sql , so you need to write three "_" as i done in my code
Also modify you code with sql parameter so taht it avoid SQL injection attack