1

I try to do this for couple of hours.

            Database db = DBUtil.GetInstance().GetDataBase();
            DbCommand cmd = db.GetSqlStringCommand(@"INSERT INTO [XXX] (
            ...
                                                                  ,[FirstDate]
            ...
            ) VALUES ('@FirstDate',...");

            db.AddInParameter(cmd, "@FirstDate", DbType.Date, DateTime.Now );

But I always get this exception information below.

{System.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting date and/or time from character string.

what should I do for the conversion ? Or pick up another DbType ? DbType.DateTime2 ?

1
  • I generally prefer to use DateTime2. It's more flexible and is a recommended practice Commented Mar 24, 2012 at 15:48

2 Answers 2

2

You don't need to add quote for parameter in Insert Statement. (Values('@FirstDate'))

    Database db = DBUtil.GetInstance().GetDataBase();
    DbCommand cmd = db.GetSqlStringCommand(@"INSERT INTO [XXX] (
    ...
                                                          ,[FirstDate]
    ...
    ) VALUES (@FirstDate,...");

   db.AddInParameter(cmd, "@FirstDate", DbType.DateTime, DateTime.Now );
Sign up to request clarification or add additional context in comments.

Comments

1

Depends on what the type is in your database if it's Date or DateTime.

// full date and time
db.AddInParameter(cmd, "@FirstDate", DbType.DateTime, DateTime.Now );

or

// just the date portion
db.AddInParameter(cmd, "@FirstDate", DbType.Date, DateTime.Now.Date );

2 Comments

That's not the problem here - see minmin's answer.
@JonSkeet, ah, yes, I see that now...but at least give me half credit for getting the other problem! :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.