以dd-MM-yyyy格式插入日期

0 c# sql-server sqlcommand datetime-format

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

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();
Run Code Online (Sandbox Code Playgroud)

我创建了一个列名为date的表具有datatype date.插入记录后,日期列字段中的值为yyyy-dd-MM格式.我希望这种dd-MM-yyyy格式.

Ste*_*eve 8

不要尝试连接字符串以构建正确的sql命令.
这只会导致解析问题和Sql注入攻击.
而是使用参数化查询

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();
}
Run Code Online (Sandbox Code Playgroud)

使用参数您不必担心如何将DateTime值格式化为字符串,您可以按照数据库字段的预期直接传递DateTime值.将此值正确传递给基础数据库表是框架作业.

对于像字符串那样的其他字段也是如此.如果您的用户在其中一个文本框中键入单引号,则会出现字符串连接的语法错误.您的用户键入的引用错误地关闭了值,将文本的其余部分保留为无效的sql文本
(例如,textCustomerName.Text = O'Brian变为....,'O'Brian' ,....)