C# Datetimepicker不使用SQL参数,而直接使用SQL注入
在编写查询以与参数一起使用时,不需要引用字符串C# Datetimepicker不使用SQL参数,而直接使用SQL注入,c#,sql,sql-injection,C#,Sql,Sql Injection,在编写查询以与参数一起使用时,不需要引用字符串 string sqlconf = ConfigurationManager.ConnectionStrings["sqlconstr"].ConnectionString; string pathconf = ConfigurationManager.AppSettings["expath"].ToString(); string sql = "select userid,logdate from Devicelogs_1_2015 where c
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();
}
应成为:
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;";
请注意,如果LogDate
是一个包含时间的类型,并且您希望忽略它,则可以将其转换为Date
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.
}
有什么问题?你还没有解释问题是什么,问题标题也不清楚。如果你想让日期像日期一样,请不要将日期存储为字符串。要仅存储不带时间元素的日期,请使用
xxxDbType.date
并传递dateTimePicker1.Value.date
。任何给定的数据库如何存储日期是一个实现细节
where cast(LogDate as date) between @fdate and @tdate