使用Date列将日期插入到sql表中

Car*_*sen 1 c# sql datetime

您好,感谢您的阅读.

我正在尝试将当前日期插入到我的表中,但我无法弄清楚如何正确编写它.

这是我的C#代码:

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString);
conn.Open();

string Comment = UserWriteComment.Text;
string ID = DetailedID.Text;
string Name = DetailedName.Text;
string UniqueID = lblID.Text;


string query = "INSERT INTO Comment(TicketID, Name, Comments, UserID, Date)" + "Values('" + ID + "', '" + Name + "', '" + Comment + "', '" + UniqueID + "', '" + Date + "')";
using (SqlCommand com = new SqlCommand(query, conn))
{
    com.ExecuteNonQuery();
    UserWriteComment.Text = "";
}
Run Code Online (Sandbox Code Playgroud)

在Query中,有一个名为Date的值.这是我喜欢将当前日期传递到我的表中的函数.

我希望你能帮助我,因为我没有设法找到答案.

谢谢:)

Tim*_*ter 7

使用DateTime.Now或(在数据库中通过sql)GetDate().但更重要的是,使用sql-parameters来防止sql注入和转换/本地化问题:

string insertSql = @"INSERT INTO Comment(TicketID, Name, Comments, UserID, Date)
                     Values(@ID, @Name, @Comment, @UniqueID, @Date)";
using (var conn = new SqlConnection("...."))
using (var com = new SqlCommand(insertSql, conn))
{
    com.Parameters.AddWithValue("@ID", ID);
    com.Parameters.AddWithValue("@Name", Name);
    com.Parameters.AddWithValue("@Comment", Comment);
    com.Parameters.AddWithValue("@UniqueID", UniqueID);
    com.Parameters.AddWithValue("@Date", DateTime.Now);
    conn.Open();
    com.ExecuteNonQuery();
}
Run Code Online (Sandbox Code Playgroud)

using语句来确保等连接非托管资源将即使在出错的情况下被布置/关闭.


Shi*_*iva 5

使用DateTime.Now而不是Date. 即将该INSERT行更新为以下内容。

string query = "INSERT INTO Comment(TicketID, Name, Comments, UserID, Date)" 
              + "Values('" + ID + "', '" + Name + "', '" + Comment + "', '" 
              + UniqueID + "', '" + DateTime.Now + "')";
Run Code Online (Sandbox Code Playgroud)

PS:您确实应该使用 Parameterize 语句来避免 Bobby Tables 情况。

在此输入图像描述

要解决此问题,请按照 @Tim 在他的回答中所示的方式实现它: