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
Related
Is it even possible to return value of string without the " " ?
I have the following string: Chb = "NOT";
Now i either want to remove the "" in C# or SQL.
so i want to have either Chb = NOT in C#
,or i want to remove the ' ' in SQL that i get in #Chb so that this:
WHERE PAR #Chb IN ('1','2','3')
isnt like this : WHERE PAR 'NOT' IN ('1','2','3')
but it is like this WHERE PAR NOT IN ('1','2','3')
I don't believe this is the right approach for this.
If you want to execute a command in SQL which comes from a C# code, then i would do:
string exists = "select * from table where var in (1,2,3)";
string notExists = "select * from table where var NOT in (1,2,3)";
if (chb != "NOT")
{
SqlCommand cmd = new SqlCommand(exists, con);
cmd.ExecuteScalar();
}
else
{
SqlCommand cmd = new SqlCommand(notExists, con);
cmd.ExecuteScalar();
}
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 created a query to oracle db
Dictionary<decimal, decimal> Dict = new Dictionary<decimal, decimal>();
string strSelectIdWork = "SELECT COLUMN FROM my_tb WHERE ROW='" + Row + "'";
dataAdapter.Fill(ds, "my_tb");
foreach (DataRow row in ds.Tables["my_tb"].Rows)
{
foreach (DataColumn column in ds.Tables["my_tb"].Columns)
{
Dict.Add(Dict.Count + 1, Convert.ToDecimal(row[column]));
}
}
foreach (decimal someVar in Dict.Values)
{
OleDbCommand command = myAccessConn.CreateCommand();
OleDbTransaction trans = myAccessConn.BeginTransaction();
command.Transaction = trans;
command.CommandText = "SELECT COLUMN FROM my_tb2 WHERE ROW='" + someVar + "'";
command.ExecuteNonQuery();
nb = Convert.ToString(command.ExecuteScalar());
comboBox2.Items.Add(nb;
trans.Commit();
}
It's working, but it takes a long time to execute and I have many queries in my function.
How can I change the code to reduce the time of the request?
I'm not too sure what you are trying to achieve, but do you realize that you are making countless connections to the database here?...
foreach (decimal someVar in Dict.Values)
{
OleDbCommand command = myAccessConn.CreateCommand();
OleDbTransaction trans = myAccessConn.BeginTransaction();
command.Transaction = trans;
command.CommandText = "SELECT COLUMN FROM my_tb2 WHERE ROW='" + someVar + "'";
command.ExecuteNonQuery();
nb = Convert.ToString(command.ExecuteScalar());
comboBox2.Items.Add(nb;
trans.Commit();
}
Whatever the total rows returned from this query...
"SELECT COLUMN FROM my_tb WHERE ROW='" + Row + "'"
will be equivalent to the total of database connections you will be opening...not to mentioned the total amount of transactions you will open as well. Do you really need to run a transaction for this select query?
Why don't you retrieve all the dictionary values into an array...
var values = Dict.Values.ToArray();
then join the values into a CSV string....
var #param = string.Join(",", values);
and pass this #params string to an IN clause
command.CommandText = "SELECT COLUMN FROM my_tb2 WHERE ROW IN(" + #param + ")";
var reader = command.ExecuteReader();
while(reader.Read())
{
comboBox2.Items.Add(reader["COLUMN"].ToString());
}
I'm omitting some details for clarity but if you need some clarifications, let me know
You really need to be using Bind Variables in these kind of situations. Oracle will parse each occurance of your query as a whole new query, which will slow things down considerably. I'm not a developer so I can't tell you how to apply this to C#, but you should start by reading this helpful article on the topic:
http://www.akadia.com/services/ora_bind_variables.html
I am trying to retrieve video name from my database where the subject of the video is like my subject to search.
I try the like query but it was not return values.
Can you kindly give the suggestions.
I am using c# with sql server.
Here is my code.
if (con.State == ConnectionState.Open)
con.Close();
con.Open();
string s1 = textBox1.Text;
cmd = new SqlCommand("select Video_Name,subject from Videos where subject like '%"+ s1 +" % ' " ,con);
//cmd = new SqlCommand("select Video_Name from Videos where subject='"+ s1+"' ", con);
SqlDataReader dr = cmd.ExecuteReader();
ArrayList a = new ArrayList();
label2.Visible = true;
label3.Visible = true;
//if (dr.Read())
{
while (dr.Read())
{
a.Add(dr[0].ToString());
}
foreach (string n in a)
{
comboBox1.Items.Add(n);
}
MessageBox.Show("Search succeded");
}
Use a parameterized query
string s1 = textBox1.Text;
cmd = new SqlCommand("select Video_Name,subject from Videos where subject like #video",con);
cmd.Parameters.AddWithValue("#video", "%" + s1 + "%");
In this way you avoid the Sql Injection problem and your command text is more readable.
This will help also in formatting your command text without subtle typing errors and without the need to add quotes around strings. With a parameter, the burden to correctly quoting the parameter value is passed to the framework code that knows better how to do it correctly.
By the way, you could avoid the second loop setting the combobox.Datasource property to the ArrayList variable a
comboBox1.Datasource = a;
Maybe it is because you have a space after the last % and its '
"select Video_Name,subject from Videos where subject like '%"+ s1 +">> % ' "<<
try something like this
"select Video_Name,subject from Videos where subject like '%"+s1+"%'"
cmd = new SqlCommand("select Video_Name,subject from Videos where subject like #vdnam",con);
cmd.Parameters.AddWithValue("#vdnam", "%" + VdName + "%");
if (dr.HasRows)
{
while (dr.Read())
{
a.Add(dr[0].ToString());
}
comboBox1.Datasource= a.List();
MessageBox.Show("Search succeded");
}
Steve's answer is of course right.
The main problem is here, your query parameter is inside single quotes. In quotes, SQL will recognize it as a string literal and never sees it as a parameter.
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.