如何将C#变量DateTime转换为SqlDbType.DateTime

时间:2012-01-06 02:09:15

标签: c# sql sql-server datetime

如何将C#DateTime变量转换为SqlDataType.DateTime的枚举?

如何将该枚举用于连接字符串?

这样做是否正确?

string str = "SELECT * FROM TABLE WHERE CreateDt " + <that enum>;
SqlConnection Connection = new SqlConnection (<connection setting>);
Table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(str, Connection);
adapter.FillSchema(Table, SchemaType.Source);
adapter.Fill(Table);

谢谢

2 个答案:

答案 0 :(得分:3)

您最好的选择是使用参数化命令:

            var cmd = new SqlCommand();
            cmd.Connection = conn;

            DateTime MyDate = DateTime.Now;

            cmd.CommandText = @"SELECT * FROM TABLE WHERE CreateDt = @MyDate";
            cmd.Parameters.AddWithValue("@MyDate", @MyDate);

            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = cmd;
            adapter.FillSchema(Table, SchemaType.Source);
            adapter.Fill(Table);

答案 1 :(得分:1)

这未经过测试,但如何:

string str = "SELECT * FROM TABLE WHERE CreateDt = @createDate";

SqlConnection Connection = new SqlConnection (<connection setting>);

Table mytable = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(str, Connection);

adapter .SelectCommand.Parameters.Add("@createDate", SqlDbType.DateTime)
adapter .SelectCommand.Parameters("@createDate").Value = <Some DateTime>

adapter.FillSchema(mytable, SchemaType.Source);
adapter.Fill(Table);