每当您发现自己将 .Net DateTime 值转换为用于 SQL 的字符串时,您就做错了。
下面演示的模式包含对问题中代码的一些改进。最值得注意的是,问题中的代码容易受到 sql 注入攻击,而这段代码则不然。但这里也有其他改进。
//most datetime comparisons want an *exclusive* upper bound, but the BETWEEN operator bounds are inclusive on both ends
var sql = "SELECT daytime AS DATE, COLUMN_2 AS SHIFT, COLUMN_3 AS 'PART NO',COLUMN_4 AS 'PART NAME',BSNO AS 'BASKET NUMBER',Spare1 AS MATERIAL, CAS6 AS 'CASCADE RINSE 6 TIME (sec)',DRY AS 'DRYER TIME (sec)',TEMP1 AS 'DRYER TEMP (°c)' FROM Table_2 WHERE daytime >= @daytimeStart AND daytime < @daytimeEnd ;";
var dt = new DataTable();
//Don't try to re-use your connection object.
// ADO.Net connection pooling means you should create a new connection for most queries
using (var con = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(sql, con))
using (var da = new SqlDataAdapter(cmd))
{ //These using blocks guarantee the connection is closed, **even if an exception is thrown**. The original code would have left the connection open if you had an exception.
//This is the correct way to include user data with your sql statement
// **NEVER** use string concatenation to substitute values into SQL strings
cmd.Parameters.Add("@daytimeStart", SqlDbType.DateTime).Value = dateTimePicker1.Value;
cmd.Parameters.Add("@daytimeEnd", SqlDbType.DateTime).Value = dateTimePicker2.Value;
//the Fill() method opens and closes the connection as needed
da.Fill(dt);
}
metroGrid1.DataSource = dt;
这里再次没有额外的注释,因此您可以看到新模式没有明显长于问题中的原始代码:
var sql = "SELECT daytime AS DATE, COLUMN_2 AS SHIFT, COLUMN_3 AS 'PART NO',COLUMN_4 AS 'PART NAME',BSNO AS 'BASKET NUMBER',Spare1 AS MATERIAL, CAS6 AS 'CASCADE RINSE 6 TIME (sec)',DRY AS 'DRYER TIME (sec)',TEMP1 AS 'DRYER TEMP (°c)' FROM Table_2 WHERE daytime >= @daytimeStart AND daytime < @daytimeEnd ;";
var dt = new DataTable();
using (var con = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(sql, con))
using (var da = new SqlDataAdapter(cmd))
{
cmd.Parameters.Add("@daytimeStart", SqlDbType.DateTime).Value = dateTimePicker1.Value;
cmd.Parameters.Add("@daytimeEnd", SqlDbType.DateTime).Value = dateTimePicker2.Value;
da.Fill(dt);
}
metroGrid1.DataSource = dt;