c# DateTime Misunderstanding [closed]

浪子不回头ぞ 提交于 2019-12-12 06:38:41

问题


No longer relevant:

In one of the comments below the OP mentions a private object DateTime() { throw new NotImplementedException(); } slipping in. It happens .


I have a DateTime field in a SqlCe database. I wish to add the time the row is created hence the need for:

DateTime now = DateTime.Now;

However this issue i am getting is that this is 'a method which is not valid in the given context'. Im guessing its something to do with it being static and im using it in a non static function perhaps ?

Just to ask in the same thread

SqlParameter Created = new SqlParameter("@Created", SqlDbType.DateTime);
**Created.Value = DateTime.Now; <--- gives error DateTime() is method which is not valid in the given context**
SqlCeCommand mySQLCommand = dbCon.CreateCommand();
mySQLCommand.CommandText = "INSERT into table (Created) VALUES (@Created)";
mySQLCommand.Parameters.Add(vetCreated);
mySQLCommand.ExecuteNonQuery(); 

Does this seem like a resonable list commands to add DateTime to the database?


回答1:


In this line:

mySQLCommand.Parameters.Add(vetCreated);

I don't know what vetCreated is, but I suppose that it's a method judging by the error message.

You should use your parameter object Created there instead.




回答2:


You can simplify your code:

mySQLCommand.CommandText = "INSERT into table (Created) VALUES (@Created)";
mySQLCommand.Parameters.AddWithValue("Created", DateTime.Now);
mySQLCommand.ExecuteNonQuery(); 

I believe this will also fix your issue as it is not clear what vetCreated is in your code.

[Update]

Not sure how you handle connection and command as your code doesn't show it. Here is the full code to insert row into a table:

using (var connection = new SqlConnection("your connection string"))
using (var command = connection.CreateCommand())
{
    command.CommandText = "INSERT into table (Created) VALUES (@Created)";
    command.Parameters.AddWithValue("Created", DateTime.Now);
    connection.Open();
    command.ExecuteNonQuery();
}


来源:https://stackoverflow.com/questions/6090577/c-sharp-datetime-misunderstanding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!