This code works
public void select()
{
string str = "SELECT * FROM gazettes g WHERE g.title LIKE '%"+ hidden_key.Value +"%' OR serial LIKE '%"+ hidden_key.Value +"%'"; /*'%' || #title || '%'*/
SqlDataSource1.SelectCommand = str;
GV_Gazette.DataBind();
}
but I want it to work in this as well but it returns an empty value. What am I doing wrong?
public void select()
{
string str = "SELECT * FROM gazettes g WHERE g.title LIKE #title OR serial LIKE #title";/*'%' || #title || '%'*/
cmd.CommandText = str;
cmd.Parameters.AddWithValue("#title", "%" + hidden_key.Value + "%");
dt = c.PopulateData(cmd);
SqlDataSource1.SelectCommand = dt.ToString();
GV_Gazette.DataBind();
}
Related
am going to explain it in pictures and Source Code
Front Design
Back-end Code
private void AddRecord(object sender, RoutedEventArgs e)
{
string date = datee.Text + " " + DateTime.Now.ToLongTimeString();
if (datee.Text == "" || cusname.SelectedValue == null || Vanda.SelectedValue == null || price.SelectedValue == null || bags.Text == "")
{
MessageBox.Show("please fill the data");
}
else
{
DataRowView dt = (DataRowView)Vanda.SelectedItem;
string vda = dt["vanda"].ToString();
DataRowView dt2 = (DataRowView)price.SelectedItem;
string data2 = dt2["price"].ToString();
decimal dta = Convert.ToDecimal(data2);
Int32 pricee = Convert.ToInt32(dta);
decimal bag = Convert.ToDecimal(bags.Text);
decimal credit = pricee * bag;
DataRowView cus = (DataRowView)cusname.SelectedItem;
string cusidd = cus["id"].ToString();
int cusid = Convert.ToInt16(cusidd);
con.Open();
SqlCommand cmd5 = new SqlCommand("SELECT price - retailprice FROM vanda where vanda = '" + vda + "' and price = '" + pricee + "'", con);
SqlDataReader reader = cmd5.ExecuteReader();
reader.Read();
string val = reader.GetValue(0).ToString();
decimal valu = Convert.ToDecimal(val);
Int32 profit = Convert.ToInt32(valu);
reader.Close();
SqlCommand cmd3 = new SqlCommand("insert into records (cusid,datee,description,vanda,price,bag,credit,debit,profit) values ('" + cusid + "','" + date + "','" + des.Text + "','" + vda + "','" + pricee + "','" + bags.Text + "','" + credit + "','','"+profit+"')", con);
cmd3.ExecuteNonQuery();
MessageBox.Show("Data Inserted");
con.Close();
}
}
DataGrid Code
private void enddate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
{
if (startdate.Text == "")
{
MessageBox.Show("Please Select Starting Date");
}
else
{
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(" i need here Query ", con);
DataSet ds = new DataSet();
adapter.Fill(ds);
data.DataContext = ds.Tables[0];
}
}
SQL Server Database
i hope you will understand it clearly. now clear the bugs and improve my code/logic/query (^_^). bla bla bla bla bla bla bla bla bla bla bla
First, your SQL should be using named parameters to avoid SQL Injection Attacks:
select r.datee,c.name,r.description,r.vanda,r.price,r.bag,r.credit,r.debit
from records as r,
customer as c
where r.cusid = c.id
and c.name = #cname
and r.datee BETWEEN #startDate AND #endDate
When you create these variables, which you will pass into your query, format them as follows:
var startDate = DateTime.Parse(datee.Text).ToString("M/d/yyyy");
var endDate = DateTime.Now.ToString("M/d/yyyy") + " 23:59:59";
This will convert the date values to the format your database expects.
select r.datee,c.name,r.description,r.vanda,r.price,r.bag,r.credit,r.debit
from records r
JOIN customer c ON r.cusid = c.id
WHERE c.name = 'aizaz' AND DateColumn BETWEEN StartDate AND EndDATE
The database doesn't store the dates in any specific string format. A date is a date and it has no specific format. Formatting the output of a date is a UI thing.
You get the actual DateTime value of a DatePicker using the SelectedDate property. You should use pass these values as parameters to your command:
SqlCommand cmd = new SqlCommand("select r.datee,c.name,r.description,r.vanda,r.price,r.bag,r.credit,r.debit from records as r, customer as c where r.cusid = c.id and c.name = #cname and r.datee BETWEEN #startDate AND #endDate");
cmd.Parameters.AddWithValue("#startDate", datePicker1.SelectedDate.Value.Date);
cmd.Parameters.AddWithValue("#endDate", datePicker2.SelectedDate.Value.Date.AddHours(23).AddMinutes(59).AddSeconds(59));
I inserted about 18 cities in government field and I can search over each city I want by ID, but now I want to search over all of the cities by ID when I do not select any thing in combobox.
string c = "%";
c = comboBox1.Text;
int a;
a = Convert.ToInt32(textBox1.Text);
a = int.Parse(textBox1.Text);
SqlCommand cmd = new SqlCommand("select * from Person where ( PER_ID = '" + a + "' and GOV_NAME_AR = '" + c + "') ", con);
cmd.CommandTimeout = 600;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
// MessageBox.Show("Successfully found Data");
// SqlDataReader DR = cmd.ExecuteReader();
BindingSource source = new BindingSource();
dataGridView1.DataSource = source;
}
else
{
MessageBox.Show("data not found");
}
con.Close();
You could change the statement in case of "nothing selected"
if (ComboBox.Text == string.Empty)
{
cmd.CommandText = "select * from Person where ( PER_ID = '" + a + "')";
}
Remarks:
use variable names like string sCity = "%"; instead of string c = "%";
use parameters for your sql statements where ( PER_ID = #Person) and cmd.Parameters.Add("#Person", SqlDbType.Int32).Value = int.Parse(textBox1.Text);
If I get you correctly, you don't want where clause on GOV_NAME_AR when combobox1 is not selected.
if( ComboBox.SelectedItem == null ) {
cmd.CommandText = "select * from Person where ( PER_ID = '" + a + "')";
}
You could do a check on the ComboBox.SelectedText like this:
if (comboBox1.SelectedText=="")
{
//SQL statement should not restrict on the c value
}
else
{
//Use your regular SQL query here.
}
I have problem when i try to filter data from datagridview. I try to filter datetime field using LIKE and % wilcard. When i assign value in textBoxEdit like this 12-01 or just put 1 am geting:
Does i not format and escape good this query string or is inposible to assign integer value to wilcard? Or maybe any other reson for this sintax error.
Another queries work fine just here i have problem:
sql = "SELECT * FROM grupe_artikala WHERE CONVERT(VARCHAR, created, 120) LIKE '" + searchTextBoxNaziv.Text + "%'";
Check my full code:
private void searchTextBoxNaziv_TextChanged(object sender, EventArgs e)
{
String selectedColumn = filterSearchCombo.Text;
String sql = "";
if(selectedColumn == "ID" && searchTextBoxNaziv.Text is string)
{
sql = "SELECT * FROM grupe_artikala WHERE id LIKE '%" + searchTextBoxNaziv.Text + "%'";
}
else if(selectedColumn == "Name")
{
sql = "SELECT * FROM grupe_artikala WHERE nameLIKE '%" + searchTextBoxNaziv.Text + "%'";
}
else if (selectedColumn == "Descr")
{
sql = "SELECT * FROM grupe_artikala WHERE desc LIKE '%" + searchTextBoxNaziv.Text + "%'";
}
else if (selectedColumn == "Created")
{
sql = "SELECT * FROM grupe_artikala WHERE CONVERT(VARCHAR, created, 120) LIKE '" + searchTextBoxNaziv.Text + "%'";
}
else
{
sql = "SELECT * FROM grupe_artikala";
}
GetData(sql);
}
Update:
private void GetData(string sql)
{
using (conn = new MySqlConnection(Properties.Settings.Default.ConnectionString))
{
try
{
conn.Open();
adapter = new MySqlDataAdapter(sql, conn);
dt = new DataTable();
bs = new BindingSource();
adapter.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
bindingNavigator1.BindingSource = bs;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
}
you don't need to convert date to varchar
SELECT * FROM grupe_artikala WHERE CONVERT(VARCHAR, created, 120) LIKE '" + searchTextBoxNaziv.Text + "%'
instead use below query
SELECT * FROM grupe_artikala WHERE created LIKE '" + searchTextBoxNaziv.Text + "%'
It will simply search data according to where condition.
This is not the problem that you stated but there needs to be a space between name and LIKE in
"SELECT * FROM grupe_artikala WHERE nameLIKE '%" + searchTextBoxNaziv.Text + "%'", because that query won't work.
As for your problem, since you are saying you are using mysql - you have a syntax error in your CONVERT it should be CONVERT(created, VARCHAR(120))
Try this.
SELECT * FROM grupe_artikala WHERE CONVERT(VARCHAR(10), created, 120) LIKE '" + searchTextBoxNaziv.Text + "%'";
Instead of
sql = "SELECT * FROM grupe_artikala WHERE CONVERT(VARCHAR, created, 120) LIKE '" + searchTextBoxNaziv.Text + "%'";
refer this link.
convert convert-datetime-to-varchar
https://technet.microsoft.com/en-us/library/ms187928(v=sql.105).aspx
OR
TRY this,
sql = "SELECT * FROM grupe_artikala WHERE LEFT(CONVERT(VARCHAR, created, 120), 10)
LIKE '" + searchTextBoxNaziv.Text + "%'";
private void searchTextBoxNaziv_TextChanged(object sender, EventArgs e)
{
String selectedColumn = filterSearchCombo.Text;
String sql = "";
if (searchTextBoxNaziv.Text.length > 0)
{
SqlCommand com = conn.CreateCommand();
com.Parameters.AddWithValue("#search", searchTextBoxNaziv.Text.ToLower());
switch (selectedColumn)
{
case "ID":
com.Parameters.AddWithValue("#searchItem", "ID");
break;
case "Name":
com.Parameters.AddWithValue("#searchItem", "Name");
break;
case "Descr":
com.Parameters.AddWithValue("#searchItem", "Desc");
break;
case "Created":
com.Parameters.AddWithValue("#searchItem", whateverCreatedIs);
break;
}
com.CommandText = "select * from grupe_artikala where lcase(#searchItem) like %#search%";
//execute SELECT
}
}
UPDATE: I'm really sorry, but I don't have MySQL installed and have to work off memory (no Intellisense). I think this will get you there or close to it. Hope it helps!
private void searchTextBoxNaziv_TextChanged(object sender, EventArgs e)
{
String selectedColumn = filterSearchCombo.Text;
String sql = "";
conn = new MySqlConnection(Properties.Settings.Default.ConnectionString);
com = new MySqlCommand("select * from grupe_artikala where lcase(#searchItem) like %#search%", conn);
if (searchTextBoxNaziv.Text.length > 0)
{
com.Parameters.AddWithValue("#search", searchTextBoxNaziv.Text.ToLower());
switch (selectedColumn)
{
case "ID":
com.Parameters.AddWithValue("#searchItem", "ID");
break;
case "Name":
com.Parameters.AddWithValue("#searchItem", "Name");
break;
case "Descr":
com.Parameters.AddWithValue("#searchItem", "Desc");
break;
case "Created":
com.Parameters.AddWithValue("#searchItem", whateverCreatedIs);
break;
}
GetData(conn, com);
}
}
private void GetData(MySqlConnection conn, MySqlCommand com)
{
try
{
conn.Open();
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = com;
dt = new DataTable();
bs = new BindingSource();
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
bindingNavigator1.BindingSource = bs;
conn.Close();
conn.Dispose();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
I need to get data from label which i had got back from previous page using Sessions from that label i need to use it to find ID for that data for example if Label contain word 'IT' it need to find its ID in database D_ID=5 code is given below
public partial class FinalFeedback1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetDataFromSession();
GetDID();
AddDynamicLabels();
}
public void GetDID()
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataReader myReader1 = null;
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
SqlCommand cmd1 = new SqlCommand(depart, connection);
myReader1 = cmd1.ExecuteReader(); // i am getting error here "Invalid column name 'IT'"
while (myReader1.Read())
{
Label9.Text = myReader1["D_ID"].ToString();
}
}
}
public void AddDynamicLabels()
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataReader myReader2 = null;
string CmdString = "Select Q_ID,Question_Data FROM QuestionTable where D_ID=" + Label9.Text + "";
SqlCommand cmd = new SqlCommand(CmdString, connection);
myReader2 = cmd.ExecuteReader();
while (myReader2.Read())
{
QID1.Text = myReader2["Q_ID"].ToString();
if (QID1.Text == ("1"))
{
Question1.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text ==("2"))
{
Question2.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("3"))
{
Question3.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("4"))
{
Question4.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("5"))
{
Question5.Text = myReader2["Question_Data"].ToString();
}
}
}
}
private void GetDataFromSession()
{
Label2.Text = Session["SNL"].ToString();
Label4.Text = Session["SNB"].ToString();
Label6.Text = Session["EMPID"].ToString();
Label8.Text = Session["DNAME"].ToString();
}
}
Change this line.
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
to this line
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
See the single quotes in the second line. Your string value is not in single quotes and this is the reason.
EDIT: Your code is open for SQL Injection Attack. You should use the SqlParameter instead of concatenating the query.
For More reading you can use this link:
http://www.w3schools.com/sql/sql_injection.asp
As simple as missing the quotations of your sql.
sql-> "where D_Name = 'somevalue'
... So the fix for your code would be
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
Change this line.
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
to
string depart = "select D_ID from Department where D_Name like '" + Label8.Text + "'";
or faster search
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
or for search similar string change to
string depart = "select D_ID from Department where D_Name like '%" + Label8.Text + "%'";
I am trying to build a web form that uses SQL queries to help populate various dropdowns and display results in gridviews, the issue i'm having at the moment is getting the user input to replace varibles in the SQL query.
My query is as follows:
SELECT TOP 50
'Select' AS 'Select',
id_ref AS 'Number',
created_date AS 'Date Created',
address 'Address',
category AS 'Category',
borough
FROM Events
WHERE location_address LIKE '%%'
AND borough #borcond
AND admin_ref #stacond
AND id_ref #Numcond
AND category #cat
AND created_date #startDate
AND created_date #endDate
AND address LIKE #Addresscond
ORDER BY id_todays_date DESC
My C# code is as follows:
public void SQLQueryv2(
string AddressSel,
string startDateSel,
string endDateSel,
string incidentSel,
string borsel,
string stasel,
string numsel)
{
//this is filled in really
SqlConnection Connection = new SqlConnection(
"Data Source=;Initial Catalog=;User=;Password=;");
string sqlquery = <<as above>>
try
{
SqlCommand Command = new SqlCommand(sqlquery, Connection);
Connection.Open();
if (borsel == "Select Borough")
{
Command.Parameters.AddWithValue("#borcond", " = IS NOT NULL ");
}
else
{
Command.Parameters.AddWithValue("#borcond","= " + "'" + borsel + "'");
}
if (stasel == "Select Town")
{
Command.Parameters.AddWithValue("#stacond", " = IS NOT NULL ");
}
else
{
Command.Parameters.AddWithValue("#borcond","= "+ "'" + borsel + "'");
}
if (startDateSel == "")
{
Command.Parameters.AddWithValue("#startDate", " = IS NOT NULL");
}
else
{
Command.Parameters.AddWithValue(
"#startDate",
">= CONVERT(datetime," + "'" + startDateSel + "'" + ",103)");
}
if (endDateSel == "")
{
Command.Parameters.AddWithValue("#endDate", " = IS NOT NULL");
}
else
{
Command.Parameters.AddWithValue(
"#endDate",
">= CONVERT(datetime," + "'" + endDateSel + "'" + ",103)");
}
if (incidentSel == "Select Category")
{
Command.Parameters.AddWithValue(
"#cat",
" in ('cat a','cat b','cat c')");
}
else
{
Command.Parameters.AddWithValue(
"#cat",
" AND category =" + "'" + incidentSel + "'");
}
if (AddressSel == "")
{
Command.Parameters.AddWithValue("#Addresscond", "%%");
}
else
{
Command.Parameters.AddWithValue("#Addresscond","%" + AddressSel + "%");
}
if (numsel == "")
{
Command.Parameters.AddWithValue("#Numcond", " = IS NOT NULL ");
}
else
{
Command.Parameters.AddWithValue("#Numcond", "= " + "'" + numsel + "'");
}
//use adapter to populate dataset...
SqlDataAdapter DataAdapter = new SqlDataAdapter(sqlquery, Connection);
DataTable DataTable = new DataTable();
DataAdapter.SelectCommand = Command;
DataAdapter.Fill(DataTable);
//then bind dataset to the gridview
GridView1.AutoGenerateColumns = true;
GridView1.DataSource = DataTable;
GridView1.DataBind();
lblResults.Visible = true;
lblResults.ForeColor = System.Drawing.Color.Green;
lblResults.Text = "Your search has returned "
+ Dataset.Tables[0].Select(
"'Incident Number' IS NOT NULL").Length.ToString()
+ " records.";
}
catch (Exception err)
{
lblResults.Visible = true;
lblResults.ForeColor = System.Drawing.Color.Red;
lblResults.Text =
"An error has occurred loading data into the table view. ";
lblResults.Text += err.Message;
}
}
When run, the Gridview doesn't populate and the query (when investigated) it still has the variables and not the 'is nulls' or user inputs.
I think its something to so with the IF statements but i'm entirely sure. I think i just need another pair of eyes on this, any help would be appreciated.
Bit more info:
If i take out the sqlCommand bits it works perfectly with the IF statements, i'm trying to stop people from using malicious SQL queries.
This really isn't the correct way to use parameters. You should only assign values to them, not add comparison operators. Here's an example of how to "fix" your query for the #borcond parameter
...
AND ((#borcond = 'Select Borough' AND borough IS NOT NULL)
OR borough = #borcond)
...
Note: you don't need the equal sign with IS NOT NULL
And replace the if-else with
Command.Parameters.AddWithValue("#borcond", borsel);
You'll need to do similar changes for all of your parameters. The trick here is to basically move your if-else logic from the code into the sql query.
Additionally I don't think you need the location_address LIKE '%%' in your query as that just matches everything.
What juhar said. You've got the wrong idea about parameters. They're parameters and not text substitution. Here's an example of a valid query:
Select firstname, lastname from contacts
where ssn = #ssn
And in your code you'd say
Command.parameters.AddWithValue("#ssn","123-45-6789")