I'm trying to insert a record in a database (Sql Server 2008) and I need to insert my date with the format dd/MM/yyyy hh:mm:ss.
I'm trying to format the value of a datapicker. This is my code:
public Manas()
{
InitializeComponent();
datep.CustomFormat = "dd/MM/yyyy hh:mm:ss";
datep.Format = DateTimePickerFormat.Custom;
}
sbQuery1S.Append("UPDATE AC SET date= '" + datep.Value.ToString() + "' WHERE NTIVO='" + txtct.Text.ToString() + "' AND NUMA ='" + txia.Text.ToString() + "' AND NUIPO='" + txtpo.Text.ToString() + "' AND SUACT='" + txtSNum.Text.ToString() + "'");
cmd1S.CommandText = sbQuery1S.ToString();
cmd1S.Connection = conn;
cmd1S.ExecuteNonQuery();
The problem is that the format of the data picker is dd//MM/yy hh:mm:ss
Any idea about how can I change it?
Never ever do this as it will cause SQL-injections vulnerability. You have to use parameters
cmd1S.CommandText = "UPDATE AC SET date = @p1 WHERE NTIVO = @p2 AND NUMA = @p3 AND NUIPO=@p4 AND SUACT=@p5";
var p1 = cmd1S.CreateParameter();
p1.Name = "p1";
p1.Value = DateTime.ParseExact(datep.Value, "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture)
cmd1S.Parameters.Add(p1);
//other parameters
cmd1S.Connection = conn;
cmd1S.ExecuteNonQuery();