Datetimepicker不能与SQL参数一起使用,而是像SQL注入一样直接使用

时间:2016-10-28 16:16:24

标签: 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 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();
}

2 个答案:

答案 0 :(得分:3)

我不确定你在问什么,但我确实看到了这些错误。

  1. 您应该在参数化查询中使用本机类型,而不是将所有内容转换为字符串。
  2. 如果您使用的是字符串,请不要将参数括在sql中的引号/标记中。但是因为这些实际上是日期或日期时间类型,所以你甚至不应该首先传递字符串。
  3. 使用块
  4. 将您的一次性物品包裹在您创建它们的位置

    我修改了代码但只包含了更改的部分。

    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;";

这应该可以解决您的问题