sql查询在sql server中执行,但不在程序上执行

时间:2014-07-12 08:01:16

标签: .net sql-server

我的程序中有这个查询:

String userSearchCommand = " select M.Title, " +
" cast(cast(cast(M.Time as float)/3600 as int) as varchar(20)) +':' " +
" +cast(cast((cast(cast(M.Time as float) as int)/60)%60 as int) as varchar(20))+':' " +
" +cast(cast(cast(cast(M.Time as float)as int)%60 as int) as varchar(20)) As WatchTime " +
" from ( select Videos.title, MAX(logging.playtime) as Time from logging " +
" inner join Videos on Videos.number = logging.viewing " +
" where username= ' " +user+ " ' and logtype = '1' and logdate>CONVERT(varchar,' " +from+ " ',110) and logdate<CONVERT(varchar,' " +to+ " ',110) " +
" group by Videos.title) M " +
" order by M.Time Desc ";

当我把特定值放在它应该执行的时候,但是当我把变量放入时,它似乎不会输出数据......有人可以帮我吗?

1 个答案:

答案 0 :(得分:2)

您应该始终使用参数化查询 - 执行 NOT 自己构建SQL命令作为字符串,包括未经验证的用户输入!这将导致SQL注入攻击 - 有史以来最常见的Web攻击。只是不要这样做。

所以不要像你知道的那样构建你的SQL命令,而是使用类似这样的东西:

string userSearchCommand = 
    @"SELECT M.Title, 
      cast(cast(cast(M.Time as float)/3600 as int) as varchar(20)) + ':' +
      cast(cast((cast(cast(M.Time as float) as int)/60)%60 as int) as varchar(20))  + ':' +
      cast(cast(cast(cast(M.Time as float)as int)%60 as int) as varchar(20)) As WatchTime 
     FROM 
        (SELECT 
            Videos.title, MAX(logging.playtime) as Time 
         FROM 
            logging 
         INNER JOIN 
            Videos ON Videos.number = logging.viewing 
         WHERE 
            username = @UserName
            AND logtype = '1' 
            AND logdate > @FromDate
            AND logdate < @ToDate
         GROUP BY 
            Videos.title) M 
    ORDER BY 
        M.Time DESC";

// create your connection and command, use the parametrized query text
using (SqlConnection conn = new SqlConnection(..your connection string here....))
using (SqlCommand cmd = new SqlCommand (userSearchCommand, conn))
{
    // define the properties and set their values
    cmd.Parameters.Add("@UserName", SqlDbType.VarChar, 100).Value = ".....";
    cmd.Parameters.Add("@FromDate", SqlDbType.DateTime).Value = ".....";
    cmd.Parameters.Add("@ToDate", SqlDbType.DateTime).Value = ".....";

    // open connection, execute query
    conn.Open();

    using (SqlDataReader reader = cmd.ExecuteReader())
    {
        // read the values
        while (reader.Read())
        {
            // do something with the values returned from the query
        }

        reader.Close();
    }

    conn.Close();
}

使用它,你避免任何SQL注入的可能性,因为你正在使用参数,查询计划将被重用,这个搜索查询的第二次和第三次执行将更快,并且从那以后如果您正在使用相应的数据类型,则可以避免日期到字符串转换,转义字符串中的单引号以及手动将SQL命令串起来时遇到的所有其他混乱问题。