在SQL中将C#datetime转换为SQL datetime [英] Convert C# datetime to SQL datetime in SQL

查看:81
本文介绍了在SQL中将C#datetime转换为SQL datetime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我将日期时间格式作为C#前端,但我想将其转换为SQL服务器中的SQL服务器日期时间格式。







请帮忙。





感谢All 。



Indrajit Dasgupta



我的尝试:



在SQL中将C#Datetime转换为SQL日期时间

Hi All,
I am getting datetime format as C# front end but I want to convert it into SQL server Datetime format in SQL server.



Please help.


Thanks to All.

Indrajit Dasgupta

What I have tried:

convert C# Datetime to SQL Datetime in SQL

推荐答案

不要将数据作为字符串传递 - 它意味着您正在连接字符串以构建SQL命令。这是非常危险的 - 它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。请改用参数化查询,并将C#DateTime值作为参数传递。如果您插入或在WHILE子句中使用的列也是DATE或DATETIME(绝对应该是这样),SQL将为您排序所有内容。

Don't pass the data as a string - it implies that you are concatenating strings to build a SQL command. And that is very dangerous - it leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead, and pass the C# DateTime value as a parameter. Provided the column you INSERT into or use in a WHILE clause is also DATE or DATETIME (which is definately should be) SQL will sort everything out for you.
DateTime startDate = new DateTime(2015, 6, 17);
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT description FROM myTable WHERE MyDateColumn > @DT", con))
        {
        cmd.Parameters.AddWithValue("@DT", startDate);
        using (SqlDataReader reader = cmd.ExecuteReader())
            {
            while (reader.Read())
                {
                string desc = (string) reader["description"];
                Console.WriteLine(desc);
                }
            }
        }
    }


这篇关于在SQL中将C#datetime转换为SQL datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆