如何将C#变量DateTime转换为SqlDbType.DateTime
本文关键字:DateTime 转换 SqlDbType 变量 | 更新日期: 2023-09-27 18:19:46
如何将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);
感谢
您的最佳选择是使用参数化命令:
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);
这没有经过测试,但怎么样:
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);