gpt4 book ai didi

c# - 将日期插入带有日期列的 sql 表中

转载 作者:太空宇宙 更新时间:2023-11-03 17:31:19 26 4
gpt4 key购买 nike

您好,感谢阅读。

我正在尝试将当前日期插入到我的表中,但我不知道如何正确写入它。

这是我的 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 = "";
}

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

我希望你能帮助我,因为我无论如何都找不到答案。

谢谢:)

最佳答案

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

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();
}

using 语句确保即使在出现错误的情况下,连接等非托管资源也将被释放/关闭。

关于c# - 将日期插入带有日期列的 sql 表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21740822/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com