如何将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);
谢谢
答案 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);