Always parameterize all your values:
using (var command = conn.CreateCommand())
{
command.CommandText = $"INSERT INTO RECORDS VALUES(@id,@ty,@ti, @d)";
command.Parameters.Add("@id", SqlDbType.VarChar, 50).Value = records.Id);
command.Parameters.Add("@ty", SqlDbType.VarChar, 50).Value = records.Type);
command.Parameters.Add("@ti", SqlDbType.VarChar, 50).Value = records.Title);
//remove this line when you’re satisfied that the inserting of times does work
records.Date = DateTime.Now;
command.Parameters.Add(new SqlParameter("@d", SqlDbType.DateTime2) { Scale = 3, Value = (object)records.Date ?? DBNull.Value });
}
I have ..
guessed you are using sql server, but if you aren’t you’ll need to use different names for the type enum than SqlDbType, which is for sql server
specified all the parameters, which you should always do because not doing so is a bad idea
switched away from using AddWithValue, because it’s a bad idea for sql server but it’s not a problem for some other DB; investigate whether it’s a good idea for you
guessed at the column types from what you said and coded. I do not believe id to actually be a string, but you put it in '
in the statement - don’t just blindly write things in '
if they aren’t strings in the db. Change the types and sizes specified to match what your columns actually are
added a test line that sets your records.Date to a date time with a time. Don’t run the code bang on midnight :) - if your property isn’t writable, make it so or swap it out out the Value and put DateTime.Now in. I assumed record.Date was a typo
If your db column is a DateTime then this code will certainly insert a date and time
Omitting the column name list from INSERT will work while your table has 4 columns but if it changes and you add another the query will fail. This is either a good thing or a bad thing. Good if you want to stop your system working while you fix the problem, bad if your new column is optional and everything could have carried on working if you’d just specified the column names. Generally it makes more sense to specify names but if you’re wanting to code more efficiently consider moving away from this style of coding, where you’re writing your own SQL, and use Entity Framework