這樣做的一種方法是對宗教使用NULL
值,並將其轉換爲%
,以便在SQL Server中進行LIKE
比較。
另外 - 我會永遠將UI代碼(事件處理程序等)從實際的數據庫訪問代碼中分離出來 - 所以在單獨的DataAccess
類中做這樣的事情(而不是直接將代碼隱藏到頁面代碼隱藏中):
public List<RuserResults> GetRuserResults(int minAge, int maxAge, string religion)
{
string selectStmt = "SELECT Age, City, State, Caste, IncomeMin, IncomeMax FROM Ruser " +
"WHERE Age BETWEEN @MinAge AND @MaxAge " +
"AND Religion LIKE @religion";
// set up your connection and command objects
using(SqlConnection conn = new SqlConnection("--your-connection-string-here--"))
using(SqlCommand cmd = new SqlCommand(selectStmt, conn))
{
// define the parameters
cmd.Parameters.Add("@MinAge", SqlDbType.Int).Value = minAge;
cmd.Parameters.Add("@MaxAge", SqlDbType.Int).Value = maxAge;
cmd.Parameters.Add("@Religion", SqlDbType.VarChar, 100);
// if you passed a value for the method parameter - use that value
if(!string.IsNullOrEmpty(religion))
{
cmd.Parameters["@Religion"].Value = religion + "%";
}
else // if no value was passed - just search for all religions
{
cmd.Parameters["@Religion"].Value = "%";
}
List<RuserResult> results = new List<RuserResult>();
// open connection, run query, close connection
conn.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
// read the values, convert to a "RuserResults", and pass it back
results.Add(ConvertReaderToRuserResult(reader));
}
}
conn.Close();
// return the results
return results;
}
}
然後從你的ASP.NET頁面,你可以調用這個
int minAge = Convert.ToInt32(drplistagemin.SelectedItem);
int maxAge = Convert.ToInt32(drplistagemax.SelectedItem);
string religion = drplistreligion.SelectedItem;
List<RuserResult> results = GetRuserResults(minAge, maxAge, religion);
// do something with the results returned here....
[SQL注入警報](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - 您應該**不**將您的SQL語句連接在一起 - 使用**參數化查詢**來代替以避免SQL注入 –