【问题标题】:Insert date in dd-MM-yyyy format以 dd-MM-yyyy 格式插入日期
【发布时间】:2014-02-01 13:46:19
【问题描述】:

我正在尝试在 c# 中以 dd-MM-yyyy 格式插入日期。插入查询是

SqlCommand cmd_cust = new SqlCommand(@"insert into custdetail values ('" + txtInvoiceNo.Text + "','" + txtCustomerName.Text + "','" + txt_contact.Text + "', '" + txtAddress.Text + "', '" + txt_total_amt.Text + "', '" + dt_date.Value.ToString("dd-MM-yyyy") + "')", con_create);
            con_create.Open();
            cmd_cust.ExecuteNonQuery();
            con_create.Close();

我创建了列名称为日期的表,其数据类型为date。插入记录后,日期列字段中的值是yyyy-dd-MM 格式。我想要dd-MM-yyyy 格式。

【问题讨论】:

  • 试试看 - ToShortDateString()
  • 我猜这是 SQL 服务器的问题,而不是 C#。数据库也会给它附加时间。
  • @user1956570 我不想系统日期格式...我想要自定义格式...
  • 别告诉我你把日期时间值存储在字符串列中
  • 不,我存储在数据类型为日期的日期列中

标签: c# sql-server datetime-format sqlcommand


【解决方案1】:

不要尝试连接字符串来构建正确的 sql 命令。
这只会导致解析问题和Sql Injection Attacks
改用参数化查询

int isok = 0;
try 
{
    // Now your query is more readable and there are no more formatting problems here
    SqlCommand cmd_cust = new SqlCommand(@"insert into custdetail values
                         (@invNo,@custName,@contact,@address,@amount,@dt)", 
                         con_create);
    con_create.Open();
    cmd_cust.Parameters.AddWithValue("@invNo",txtInvoiceNo.Text );
    cmd_cust.Parameters.AddWithValue("@custName",txtCustomerName.Text );
    cmd_cust.Parameters.AddWithValue("@contact",txt_contact.Text);
    cmd_cust.Parameters.AddWithValue("@address",txtAddress.Text.Text);
    // The following parameter could require a conversion if the db field is not of text type
    // cmd_cust.Parameters.AddWithValue("@amount", Convert.ToDecimal(txt_total_amt.Text)); 
    cmd_cust.Parameters.AddWithValue("@amount", txt_total_amt.Text); 
    cmd_cust.Parameters.AddWithValue("@dt",dt_date.Value );
    isok= cmd_cust.ExecuteNonQuery();
    con_create.Close();
}

使用参数,您无需担心如何将 DateTime 值格式化为字符串,您可以按照数据库字段的预期直接传递 DateTime 值。将这个值正确地传递给底层数据库表是框架的工作。

对于字符串字段等其他字段也是如此。如果您的用户在其中一个文本框中键入单引号,您会收到字符串连接的语法错误。您的用户输入的引号错误地关闭了值,使文本的其余部分成为无效的 sql 文本
(例如,textCustomerName.Text = O'Brian 变为 ....,'O'Brian' ,....

【讨论】:

    【解决方案2】:

    我同意史蒂夫上面的回答。但是,为了专注于您的具体问题,SQL 不会以特定格式存储日期 - 它将日期存储为两个整数(二进制)。因此,您在查询窗口(或您正在查看的其他任何地方)中看到的日期无关紧要;同样,您尝试插入数据库的任何格式都无关紧要(只要 SQL Server 可以正确解析它)。如果您希望输出以某种方式显示,您可以重新格式化以满足您对 SELECT 查询的需求。 SQL 和 C# 都有广泛的日期格式化方法。

    您是在 SQL 查询输出还是 C# 程序输出中格式化日期?

    【讨论】:

    • 我用 dt_date.Value.ToString("dd-MM-yyyy") 这个来改变格式
    • 这不是真的。您正在尝试更改数据库输入端的格式,这不相关。如果你想改变格式,它必须在输出端完成。
    • 如何在输出端进行更改。?
    • 有很多方法。这取决于您的最终用户将如何/在何处查看它。请进一步描述。
    • 其实我想将所选日期之间的记录显示为@"select invoiceid,custname,contact,date,totalfees from custdetail where date between '" + dt_from.Value.ToString("dd-MM-yyyy ") + "' 和 '" + dt_to.Value.ToString("dd-MM-yyyy") + "'"
    猜你喜欢
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多