Search code examples
c#mysqlsqlsql-insertlast-insert-id

How do I insert into a datetime column minus the seconds?


So I'm working on a c# project that creates row in a table with a datetime column and then extract that auto generated ID of that column afterwards. My way of extracting the ID is through the code below the problem is the length it takes to execute the first query and then the second query is more than 1 second so I end up getting empty rows. So how do I insert or select rows minus the seconds?

INSERT INTO transactionlog(transactionDate) VALUES(NOW())

AND THEN IMMEDIATELY THIS

SELECT transactionID,transactionDate FROM transactionlog WHERE transactionDate=NOW();


Solution

  • NOW() gives you the date/time when the statement it contains started. While it is guaranteed that several invokations in the same query return the same value, this is not true accross queries.

    To get the auto-incremented value generated during an insert, you can use LAST_INSERT_ID() instead:

    INSERT INTO transactionlog(transactionDate) VALUES(NOW());
    SELECT LAST_INSERT_ID();