Asp.net 在数据库中插入日期时间

Asp.net 在数据库中插入日期时间,asp.net,sql,datetime,Asp.net,Sql,Datetime,我的SQL数据库中有一个DateTime字段,我想将时间写入该字段,但我该怎么做呢 我希望将其作为时间戳,因此当用户单击“添加”按钮时,它会将数据添加到其他字段中,并将时间戳添加到DateTime字段中,但我不断得到以下错误 从字符串转换日期和/或时间时,转换失败 这是我在CS文件中的当前代码 insertSQL = "INSERT INTO Posts (TopicID, PostBody, PostDate, UserID)" + "VALUES ('" + topic +

我的SQL数据库中有一个DateTime字段,我想将时间写入该字段,但我该怎么做呢

我希望将其作为时间戳,因此当用户单击“添加”按钮时,它会将数据添加到其他字段中,并将时间戳添加到DateTime字段中,但我不断得到以下错误

从字符串转换日期和/或时间时,转换失败

这是我在CS文件中的当前代码

insertSQL = "INSERT INTO Posts (TopicID, PostBody, PostDate, UserID)"
        + "VALUES ('" + topic + "', '" + newPostText + "', '" + DateTime.Now.ToString() + "', '" + User_ID + "')";

请注意,我想显示尽可能多的时间信息。2012年5月23日上午10:58:00

你要的是标准时间吗



唉,我的错,是Php的错~

您的实现很容易
SQL注入
。要解决此问题以及日期时间问题,请使用参数-

大概是这样的:

string commandText = "INSERT INTO Posts (TopicID, PostBody, PostDate, UserID)"
    + "VALUES (@Topic, @NewPostText, @PostDate, @UserID)";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(commandText, connection);
    command.Parameters.AddWithValue("@Topic", "My Topic");
    command.Parameters.AddWithValue("@NewPostText", "Post text goes here");
    command.Parameters.AddWithValue("@PostDate", dateObject);
    command.Parameters.AddWithValue("@UserID", "UserA");

    try
    {
        connection.Open();
        Int32 rowsAffected = command.ExecuteNonQuery();
    }
    catch (Exception)
    {
        // Handle Errors    
    }
}

谢谢我知道它目前很容易发生,但这并没有回答我的问题,使用参数就是你问题的答案。参数可以保留数据类型,因此,SQL引擎不会将DateTime作为字符串注入SQL并强制SQL尝试将其转换回DateTime,而是会收到一个DateTime对象。+1用于将较差的链接答案更改为带有链接作为引用的真实答案。我现在理解了。很抱歉谢谢:)。谢谢你的帮助。对不起,我不熟悉asp.net。祝你好运。1:欢迎来到StackOverflow!不幸的是,你没有回答这个问题。在回答有关asp.net问题的问题时,解决方案可能涉及asp.net,而不是php。当回答一个关于向数据库中插入值的问题时,正确的答案很可能会说明向数据库中插入值,而不仅仅是格式化它。查看@Snixtor的答案,看看您可以如何改进您的解决方案。实际上,我认为没有必要~在寻找解决方案时,我们只需要提示,而不需要完整的解决方案。在SQL Server中,将smalldatetime的“默认值或绑定”设置为(getdate())
string commandText = "INSERT INTO Posts (TopicID, PostBody, PostDate, UserID)"
    + "VALUES (@Topic, @NewPostText, @PostDate, @UserID)";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(commandText, connection);
    command.Parameters.AddWithValue("@Topic", "My Topic");
    command.Parameters.AddWithValue("@NewPostText", "Post text goes here");
    command.Parameters.AddWithValue("@PostDate", dateObject);
    command.Parameters.AddWithValue("@UserID", "UserA");

    try
    {
        connection.Open();
        Int32 rowsAffected = command.ExecuteNonQuery();
    }
    catch (Exception)
    {
        // Handle Errors    
    }
}