0

I have next code C#:

cm.CommandText = "Select * from H_Facturi_Clienti where Serie like '" + TextBox1.Text + "%' and Numar like '" + textBox2.Text + "%' and Data >= '"+dateTimePicker1.Text+"'";

I know this doesn't work because my datetimepicker is short format: dd/MM/yyyy and Data in sql is smalldatetime: yyyy/MM/dd hh:mm:ss

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
alexg
  • 19
  • 3

1 Answers1

2

You have a bad habits to kick which you try to send string to a column which is typed smalldatetime.

Send it's Value property directly, not it's string representation.

But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.

using(var con = new SqlConnection(conStr))
using(var cm = con.CreateCommand())
{
   cm.CommandText = @"Select * from H_Facturi_Clienti 
                      where Serie like @serie and Numar like @numar and Data >= @data";
   cm.Parameters.Add("@serie", SqlDbType.NVarChar).Value = TextBox1.Text + "%";
   cm.Parameters.Add("@numar", SqlDbType.NVarChar).Value = textBox2.Text + "%";
   cm.Parameters.Add("@data",  SqlDbType.SmallDateTime).Value = dateTimePicker1.Value;
   // Do whatever you want
}

Also SELECT * is quite bad. Read Why is SELECT * considered harmful?

As a last thing, Data (ignoring it's case) could be reserved keyword in future releases of SQL Server. You might wanna use it as [Data] but as a best practice, change it to non-reserved word.

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364