Problems with SELECT with 2 WHEREs

4

I have a somewhat amateurish problem here. I can not do this SELECT from 2 CONDITIONS, and I can not find the ERROR! Someone please give me a light there!

Follow the Code:

OleDbConnection Con = new OleDbConnection();
Con.ConnectionString = Properties.Settings.Default.dbConnection;

Con.Open();
OleDbCommand Cmm = new OleDbCommand();

Cmm.CommandText = "SELECT CodAutomaticProd, DescProd, BrandCod FROM tbProdutos WHERE ModelProd LIKE '%" + txtModel.Text + "%' AND YearProd LIKE '%" + txtYear.Text + " %' ";

Cmm.CommandType = CommandType.Text;
Cmm.Connection = Con;

OleDbDataReader DR;
DR = Cmm.ExecuteReader();

listBox1.Items.Clear();

while (DR.Read())
{
    listBox1.Items.Add(DR.GetInt32(0) + " - " + DR.GetString(1) + " -    " + DR.GetString(2));
}

The code runs perfectly within the BANK, and is within TRY which does not indicate ERROR by "Exception".

    
asked by anonymous 26.07.2016 / 22:53

3 answers

8

Has a blank space in the string before finishing the last LIKE

txtYear.Text + "( here )% '

    
26.07.2016 / 23:05
7

The correct way to do this is by using parameterization. This way, you can inject unwanted SQL code into your query:

Cmm.CommandText = "SELECT CodAutomaticProd, DescProd, BrandCod FROM tbProdutos WHERE ModelProd LIKE '%@ModelProd%' AND YearProd LIKE '%@YearProd%' ";
Cmm.Parameters.Add(new SqlParameter("@ModelProd", txtModel.Text));
Cmm.Parameters.Add(new SqlParameter("@YearProd", txtYear.Text));
    
26.07.2016 / 23:12
0

White space "% '"

Like should be '% value%'

    
29.07.2016 / 03:23