繁体   English   中英

如何将PC的当前日期和时间添加到“ SQL Server数据库”列中?

[英]How do I add my PC's current date and time into SQL Server Database column?

我有一个代码,其中我使用querystring方法将数据插入SQL Server,如下所示,

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值。

您可以在表测试中添加一列,将其命名为CreatedDate并将默认值设置为GETDATE()

默认

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

GETDATE()

以不带数据库时区偏移的日期时间值返回当前数据库系统时间戳。 此值是从运行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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM