如何将电脑的当前日期和时间添加到 SQL Server 数据库列中

本文关键字:SQL Server 数据库 添加 时间 电脑 当前日期 | 更新日期: 2023-09-27 18:36:17

我有一个代码,其中我使用查询字符串方法将数据插入SQL服务器,如下所示,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["x"] != null)
        {
            if (Request.QueryString["y"] != null)
            {
                insertData();
            }
        }
     //   else
      //  {
     //         Response.Redirect("http://localhost:53627/Default.aspx");
     //   }

    }
    public void insertData()
    {
        using (SqlConnection con = new SqlConnection(GetConnectionString()))
        {
            con.Open();
            try
            {
                using (SqlCommand cmd = new SqlCommand("INSERT INTO Test(x, y) VALUES(@x, @y)", con))
                {
                    cmd.Parameters.Add(new SqlParameter("x", Request.QueryString["x"]));
                    cmd.Parameters.Add(new SqlParameter("y", Request.QueryString["y"]));
                    cmd.ExecuteNonQuery();
                }
            }   
            catch (Exception Ex)
            {
               // Console.WriteLine("Unable To Save Data. Error - " + Ex.Message);
                Response.Write("Unable To Save Data. Error - " + Ex.Message);
            }
        }
    }
    public string GetConnectionString()
    {
        //sets the connection string from the web config file "ConnString" is the name of the Connection String
        return System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
    }
}

现在在这个当前的代码中,我需要添加系统的日期和时间以及 x 和 y 值。有什么指导吗?

如何将电脑的当前日期和时间添加到 SQL Server 数据库列中

你可以向表测试添加一个列,让我们称之为 CreatedDate 并将默认值设置为 GETDATE()

违约

指定在值不是时为列提供的值 在插入期间显式提供。默认定义可以是 应用于除定义为时间戳的列或那些 与 IDENTITY 属性。如果为 用户定义的类型列,该类型应支持隐式 从constant_expression转换为用户定义类型。违约 删除表时,将删除定义。只有一个常数 值,例如字符串;标量函数(系统, 用户定义或 CLR 函数);或 NULL 可用作默认值。自 保持与早期版本的 SQL Server 的兼容性,一个 可以将约束名称分配给默认值。

获取日期()

以日期时间值的形式返回当前数据库系统时间戳 没有数据库时区偏移量。此值派生自 SQL Server 实例所在的计算机的操作系统 正在运行。

SQL 小提琴演示

事后想想,如果要从 C# 发送 DateTime 值,可以使用 DateTime.Now 将代码更改为类似

获取设置为当前日期和时间的 DateTime 对象 此计算机,表示为本地时间。

using (SqlCommand cmd = new SqlCommand("INSERT INTO Test(x, y, dt) VALUES(@x, @y, @dt)", con))
{
    cmd.Parameters.Add(new SqlParameter("x", Request.QueryString["x"]));
    cmd.Parameters.Add(new SqlParameter("y", Request.QueryString["y"]));
    cmd.Parameters.Add(new SqlParameter("dt", DateTime.Now));
    cmd.ExecuteNonQuery();
}