string sqlconf = ConfigurationManager.ConnectionStrings["sqlconstr"].ConnectionString;
string pathconf = ConfigurationManager.AppSettings["expath"].ToString();
string sql = "select userid,logdate from Devicelogs_1_2015 where convert(varchar(10),LogDate,103) between '@fdate' and '@tdate';";
StreamWriter sw = new StreamWriter(pathconf);
SqlConnection sqlcon = new SqlConnection(sqlconf);
SqlCommand sqlcom = new SqlCommand(sql, sqlcon);
sqlcom.Parameters.Add("@fdate", SqlDbType.VarChar).Value = dateTimePicker1.Value.ToString("dd/MM/yyyy");
sqlcom.Parameters.Add("@tdate", SqlDbType.VarChar).Value = dateTimePicker2.Value.ToString("dd/MM/yyyy");
sqlcon.Open();
using (sqlcon)
{
using (SqlDataReader sqldr = sqlcom.ExecuteReader())
{
while (sqldr.Read())
{
string userid1 = sqldr.GetString(0);
DateTime logdate1 = sqldr.GetDateTime(1);
sw.WriteLine("{0},{1}", userid1, logdate1.ToString("yyyy-MM-dd HH:mm:ss"));
}
sw.Close();
sqldr.Close();
}
sqlcon.Close();
MessageBox.Show("File Exported Successfully");
Close();
}
答案 0 :(得分:3)
我不确定你在问什么,但我确实看到了这些错误。
我修改了代码但只包含了更改的部分。
string sql = "select userid,logdate from Devicelogs_1_2015 where LogDate between @fdate and @tdate";
using(SqlConnection sqlcon = new SqlConnection(sqlconf))
using(SqlCommand sqlcom = new SqlCommand(sql, sqlcon))
{
sqlcom.Parameters.Add("@fdate", SqlDbType.Date).Value = dateTimePicker1.Value.Date;
sqlcom.Parameters.Add("@tdate", SqlDbType.Date).Value = dateTimePicker2.Value.Date;
sqlcon.open();
// rest of the code that executes the query etc.
}
请注意,如果LogDate
是包含时间的类型,并且您想省略它,则可以将其转换为Date
。
where cast(LogDate as date) between @fdate and @tdate
答案 1 :(得分:0)
当您编写要与参数一起使用的查询时,您不需要引用字符串。
string sql = "select userid,logdate from Devicelogs_1_2015 where convert(varchar(10),LogDate,103) between '@fdate' and '@tdate';";
应该成为:
string sql = "select userid,logdate from Devicelogs_1_2015 where convert(varchar(10),LogDate,103) between @fdate and @tdate;";
这应该可以解决您的问题