SQL Injection prevention to generate parameterized General paging query statements

Source: Internet
Author: User
Tags sql injection prevention

If you want to prevent SQL injection, you can only filter the input parameters. For example, you can convert a single quotation mark (') into two single quotation marks (''). however, this approach is not safe. Hackers can bypass single quotes filtering by encoding. to effectively prevent SQL injection, only parameterized query is the final solution. But the problem is that this general paging storage process concatenates SQL statements in the stored procedure and cannot be modified to parameterized query statements. Therefore, this general paging storage process is not desirable. However, if you do not need a general paging stored procedure, it means that you must write a paging stored procedure for each specific paging query, which will increase the workload.
After several days of consideration, I came up with a solution to generate parameterized generic paging query statements using code. The Code is as follows:
Copy codeThe Code is as follows:
Public class PagerQuery
{
Private int _ pageIndex;
Private int _ pageSize = 20;
Private string _ pk;
Private string _ fromClause;
Private string _ groupClause;
Private string _ selectClause;
Private string _ sortClause;
Private StringBuilder _ whereClause;
Public DateTime DateFilter = DateTime. MinValue;
Protected QueryBase ()
{
_ WhereClause = new StringBuilder ();
}
/** // <Summary>
/// Primary key
/// </Summary>
Public string PK
{
Get {return _ pk ;}
Set {_ pk = value ;}
}
Public string SelectClause
{
Get {return _ selectClause ;}
Set {_ selectClause = value ;}
}
Public string FromClause
{
Get {return _ fromClause ;}
Set {_ fromClause = value ;}
}
Public StringBuilder WhereClause
{
Get {return _ whereClause ;}
Set {_ whereClause = value ;}
}
Public string GroupClause
{
Get {return _ groupClause ;}
Set {_ groupClause = value ;}
}
Public string SortClause
{
Get {return _ sortClause ;}
Set {_ sortClause = value ;}
}
/** // <Summary>
/// Current page number
/// </Summary>
Public int PageIndex
{
Get {return _ pageIndex ;}
Set {_ pageIndex = value ;}
}
/** // <Summary>
/// Page size
/// </Summary>
Public int PageSize
{
Get {return _ pageSize ;}
Set {_ pageSize = value ;}
}
/** // <Summary>
/// Generate the cache Key
/// </Summary>
/// <Returns> </returns>
Public override string GetCacheKey ()
{
Const string keyFormat = "Pager-SC: {0}-FC: {1}-WC: {2}-GC: {3}-SC: {4 }";
Return string. Format (keyFormat, SelectClause, FromClause, WhereClause, GroupClause, SortClause );
}
/** // <Summary>
/// SQL statement that generates the total number of query records
/// </Summary>
/// <Returns> </returns>
Public string GenerateCountSql ()
{
StringBuilder sb = new StringBuilder ();
Sb. AppendFormat ("from {0}", FromClause );
If (WhereClause. Length> 0)
Sb. AppendFormat ("where 1 = 1 {0}", WhereClause );
If (! String. IsNullOrEmpty (GroupClause ))
Sb. AppendFormat ("group by {0}", GroupClause );
Return string. Format ("Select count (0) {0}", sb );
}
/** // <Summary>
/// Generate a paging query statement, including the total number of records
/// </Summary>
/// <Returns> </returns>
Public string GenerateSqlIncludeTotalRecords ()
{
StringBuilder sb = new StringBuilder ();
If (string. IsNullOrEmpty (SelectClause ))
SelectClause = "*";
If (string. IsNullOrEmpty (SortClause ))
SortClause = PK;
Int start_row_num = (PageIndex-1) * PageSize + 1;
Sb. AppendFormat ("from {0}", FromClause );
If (WhereClause. Length> 0)
Sb. AppendFormat ("where 1 = 1 {0}", WhereClause );
If (! String. IsNullOrEmpty (GroupClause ))
Sb. AppendFormat ("group by {0}", GroupClause );
String countSql = string. Format ("Select count (0) {0};", sb );
String tempSql =
String. Format (
"WITH t AS (SELECT ROW_NUMBER () OVER (order by {0}) as row_number, {1} {2 }) select * from t where row_number BETWEEN {3} and {4 };",
SortClause, SelectClause, sb, start_row_num, (start_row_num + PageSize-1 ));
Return tempSql + countSql;
}
/** // <Summary>
/// Generate a paging query statement
/// </Summary>
/// <Returns> </returns>
Public override string GenerateSql ()
{
StringBuilder sb = new StringBuilder ();
If (string. IsNullOrEmpty (SelectClause ))
SelectClause = "*";
If (string. IsNullOrEmpty (SortClause ))
SortClause = PK;
Int start_row_num = (PageIndex-1) * PageSize + 1;
Sb. AppendFormat ("from {0}", FromClause );
If (WhereClause. Length> 0)
Sb. AppendFormat ("where 1 = 1 {0}", WhereClause );
If (! String. IsNullOrEmpty (GroupClause ))
Sb. AppendFormat ("group by {0}", GroupClause );
Return
String. Format (
"WITH t AS (SELECT ROW_NUMBER () OVER (order by {0}) as row_number, {1} {2 }) select * from t where row_number BETWEEN {3} and {4 }",
SortClause, SelectClause, sb, start_row_num, (start_row_num + PageSize-1 ));
}
}

Usage:

Copy codeThe Code is as follows:
PagerQuery query = new PagerQuery ();
Query. PageIndex = 1;
Query. PageSize = 20;
Query. PK = "ID ";
Query. SelectClause = "*";
Query. FromClause = "TestTable ";
Query. SortClause = "id desc ";
If (! String. IsNullOrEmpty (code ))
{
Query. WhereClause. Append ("and ID = @ ID ");
}

A) The GenerateCountSql () method generates the following statement:
Select count (0) from TestTable Where 1 = 1 and ID = @ ID
B) The GenerateSql () method generates the following statement:
WITH t AS (SELECT ROW_NUMBER () OVER (order by ecid desc) as row_number, * from TestTable where 1 = 1 and ID = @ ID) select * from t where row_number BETWEEN 1 and 20
C) The GenerateSqlIncludetTotalRecords () method generates the following statement:
WITH t AS (SELECT ROW_NUMBER () OVER (order by e. ecid desc) as row_number, * from TestTable where 1 = 1 and ID = @ ID) Select * from t where row_number BETWEEN 1 and 20; Select count (0) from ECBasicInfo where 1 = 1 and ID = @ ID;

Note: The SQL statements generated by the above Code were used for SQL server 2005 and later versions. I hope these codes will be useful to you.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.