C# replace parameters in query with defined values [duplicate] - c#

This question already has answers here:
parameterized queries vs. SQL injection
(4 answers)
Closed 6 years ago.
string[] theParms = ['parm1', 'parm2'];
string theQuery = "SELECT something, somethingAgain " +
"FROM aDBTable " +
"WHERE something = '{?}'" +
"AND something <> '{?}'";
I am needing to replace the {?}'s with the defined parms in theParms.
Is there some type of loop in C# that I can use in order to loop through the string and replace each found {?} with the corresponding parm value?
Something like this:
First loop:
SELECT something, somethingAgain
FROM aDBTable
WHERE something = 'parm1' AND something <> '{?}'
Second loop:
SELECT something, somethingAgain
FROM aDBTable
WHERE something = 'parm1' AND something <> 'parm2'
Is there some type of REGEX or common framework function that can do the above?
sql injection check
bool injectionCheckin = new injectionCheck().inCheck(theFinalQuery);
public class injectionCheck
{
public bool inCheck(string queryString)
{
var badWords = new[] {
"EXEC", "EXECUTE", ";", "-", "*", "--", "#",
"UNION", "DROP","DELETE", "UPDATE", "INSERT",
"MASTER", "TABLE", "XP_CMDSHELL", "CREATE",
"XP_FIXEDDRIVES", "SYSCOLUMNS", "SYSOBJECTS",
"BC_HOME_ADDRESS1", "BC_HOME_ADDRESS2", "BC_HOME_CITY", "BC_HOME_COUNTY", "BC_HOME_POSTAL", "BC_MAIL_ADDRESS1",
"BC_MAIL_ADDRESS2", "BC_MAIL_CITY", "BC_MAIL_COUNTY", "BC_MAIL_POSTAL", "BC_MAIL_STATE", "FLSA_STATUS", "GRADE",
"GRADE_ENTRY_DT", "HIGHEST_EDUC_LVL", "LAST_INCREASE_DT", "BC_SALP_DESCR", "BC_SALP_DESCRSHORT", "SAL_ADMIN_PLAN"
};
string pattern = "(?<!\\w)(" + Regex.Escape(badWords[0]);
foreach (var key in badWords.Skip(1))
{
pattern += "|" + Regex.Escape(key);
}
pattern += ")(?!\\w)";
dynamic _tmpCount = Regex.Matches(queryString, pattern, RegexOptions.IgnoreCase).Count;
if (_tmpCount >= 1)
return true;
else
return false;
}
}

Always create Sql-commands by parameterized queries:
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
using (SqlCommand cmd = conn.CreateCommand())
{
var #params = new Dictionary<string, object>{
{ "something", myValue },
{ "somethingDifferent", anotherValue },
};
cmd.CommandText = "SELECT something, somethingAgain " +
"FROM aDBTable " +
"WHERE something = #something'" +
"AND something <> #somethingDifferent'";
foreach (KeyValuePair<string, object> item in values)
{
cmd.Parameters.AddWithValue("#" + item.Key, item.Value);
}
DataTable table = new DataTable();
using (var reader = cmd.ExecuteReader())
{
table.Load(reader);
return table;
}
}
}
This prevents all sort of SqlInjection and you won´t any weird checks as yours with the badlist which is quite messy and does not really prevent you, you can easily bypass the list with some escaping for instance. In particular: why do you want to write your own validation when there allready are ready-to-use methods that do exactly what you want?

Why not just use String.Format?
string[] theParms = new string[] { "parm1", "parm2" };
string theQuery = #"SELECT something, somethingAgain
FROM aDBTable
WHERE something = '{0}'
AND something <> '{1}'";
var res = string.Format(theQuery, theParms);
Result:
SELECT something, somethingAgain
FROM aDBTable
WHERE something = 'parm1'
AND something <> 'parm2'

If you want to do it in either case, you could do it without a loopy as follows.
string theQuery = String.Format( "SELECT something, somethingAgain " +
"FROM aDBTable " +
"WHERE something = '{0}'" +
"AND something <> '{1}'",
theParams[0], theParams[1] );

Okay, to avoid Injection and all that, why don't you do it like this:
string[] theParms = // initialization
string theQuery = // initialization
SqlCommand cmd = new SqlCommand(/* enter connection string */, theQuery)
for(int i = 0; i < theParams.Length; i++)
{
int index = cmd.Text.IndexOf("{?}");
if(index > -1)
{
string pName = string.Format("#p{0}", i);
cmd.Text = cmd.Text.Remove(index, 3).Insert(index, pName);
cmd.Parameters.Add(new SqlParameter() { Name = pName, Value = theParms[i] });
}
}
That should avoid any manual injection checks alltogether... at least if you can't get the query pre-compiled and have to load it at runtime. Otherwise just formulate the SqlCommand's text appropriately and you'll not need a loop or anything. Just a simple initialization:
SqlCommand cmd = new SqlCommand(/* enter connection string */, "SELECT something, somethingAgain FROM aDBTable WHERE something = #p0 AND something <> #p1");
cmd.Parameters.Add(new SqlParameter() { Name = "#p0", Value = theParms[0] });
cmd.Parameters.Add(new SqlParameter() { Name = "#p1", Value = theParms[1] });

You can use IndexOf and substrings to find each instance
for(int i = 0; i < theParms.GetLength(0); i++)
{
string[] tempStrings = new string[]{ theQuery.Substring(0,theQuery.IndexOf("{?}") - 1),
theQuery.Substring(theQuery.IndexOf("{?}"), 3),
theQuery.Substring(theQuery.IndexOf("{?}") + 4) }
tempStrings[1] = tempStrings[1].Replace("{?}", theParms[i]);
theQuery = String.Join("", tempStrings);
}
Though seeing as you check for injection afterwards it is definitely much better to use String.Format

You don't have to handle it by yourself. Instead, ADO.NET allows you define parameters and set their values. See the sample here .MSDN

Related

Passing a dynamic array of SqlParameters into a SQL string IN clause

I have a way to write a SqlCommand which includes a dynamic list of parameters.
My challenge is passing each of the new SqlParameter (#Param0, value0), new sqlParameter (#Param1, value1)... could be another 50 SQL parameters. It can be passed as a hard-coded string but passing the sb.ToString() understandably won't work (because of the commas - they are new arguments).
How do I write a loop or similar to pass the correct number of new arguments?
My attempt so far is below:
public ViewResult Index(int? ID)
{
using (var context = new Projects201819Context())
if (ID == null)
{
var sqlCommand = new SqlCommand();
// Array of item numbers - will change and can be longer/shorter, as required.
var SQL0 = "SELECT * FROM [database] WHERE material_id IN ({0})";
var idList = new List<int> { 11, 53, 125};
int[] idListArray = idList.ToArray();
var idParameterList = new List<string>();
var index = 0;
int IL = idList.Count;
// Create a SqlParameter for each element in the array called "#idParam0", "#idParam1"... and add to list idParameterList
foreach (var id in idList)
{
var paramName = "#idParam" + index;
sqlCommand.Parameters.AddWithValue(paramName, id);
idParameterList.Add(paramName);
index++;
}
// Finalise SQL String for datainput - DONE AND WORKS
sqlCommand.CommandText = String.Format(SQL0, string.Join(",", idParameterList));
var newSPList = new List<string>();
var m = 0;
foreach (var id in idList)
{
var SPName = " new SqlParameter(" + "\"" + "#idParam" + m + "\"" + "," + idListArray[m] + ")";
newSPList.Add(SPName);
m++;
}
string HELLO = string.Join(",", newSPList);
string MM = "\"" + sqlCommand.CommandText + "\"" + "," + HELLO;
var datainput = context.materials.SqlQuery(MM);
var data = datainput.ToList();
return View(data);
}
}
where there is an id is fine and not given (the else part of if (id == null)).
The critical bit is the SPName - this successfully adds items to the newSPList list and the string.join returns the exact string I need (HELLO) but I can't then pass this long string as separate arguments - makes complete sense - I just don't know how to work around it!
Thank you for any support!
Let SQL Server do all dirty work. Something like this.
var SQL0 = "SELECT * FROM [database] WHERE material_id IN (select value from string_split('{0}',','))";
var idList = new List<int> { 11, 53, 125};
int[] idListArray = idList.ToArray();
sqlCommand.CommandText = String.Format(SQL0, string.Join(",", idListArray));
// now execute the command
EDIT
More secure and performat way.
var SQL0 = "SELECT * FROM [database] WHERE material_id IN (select value from string_split(#ids,','))";
var idList = new List<int> { 11, 53, 125};
int[] idListArray = idList.ToArray();
sqlCommand.CommandText = SQL0;
sqlCommand.Parameters.Add("#ids", SqlDbTypes.VarChar, -1).Value = string.Join(",", idListArray);
// now execute the command
You cannot pass an array of parameters in that way. SqlQuery from EF6 has an overload that accepts, as second parameter, an array of SqlParameter.
All you have to do is:
SqlParameter[] pms = sqlCommand.Parameters.Cast<SqlParameter>().ToArray();
var datainput = context.materials.SqlQuery(sqlCommand.CommandText, pms);
Of course this means also that a lot of your current code is unnecessary and you can scrap it away
For example, you could write this without an SqlCommand object used just to store parameters and the command text.
var SQL0 = "SELECT * FROM [database] WHERE material_id IN ({0})";
var idList = new List<int> { 11, 53, 125 };
var idParameterList = new List<string>();
var pms = new List<SqlParameter>();
int count = 1;
foreach (var id in idList)
{
var paramName = "#idParam" + count++;
SqlParameter p = new SqlParameter(paramName, SqlDbType.Int);
p.Value = id;
pms.Add(p);
idParameterList.Add(paramName);
}
string cmdText = String.Format(SQL0, string.Join(",", idParameterList));
var datainput = context.materials.SqlQuery(cmdText, pms);

OleDbCommand with 'where in' and dbParameter

I try to delete some rows from a table in an access database file via C#.
This attempt fails with no error which leads me to the conclusion that I have a valid query with incorrect data.
I tried to see if I can query the data with a select statement from my code and I can narrow the problem down to the parameters.
The statement should look as follows
SELECT * FROM tbIndex where pguid in ('4a651816-e15b-4c6a-85c4-74033ca6c423', '0add7bff-a22f-4238-9c7f-e1ff4ed3c7e2', '742fae8b-2692-4a6f-802c-848fad570696', '5e6b65de-2403-4800-a47d-e57c7bd8e0a6')
I tried two different ways*(dbCmd2 and dbCmd3)* from which the first*(dbCmd2)* works but is, due to injection problems, not my prefered solution.
using (OleDbCommand dbCmd2 = new OleDbCommand { Connection = m_Connection })
{
dbCmd2.CommandText = "SELECT * FROM tbIndex where pguid in ("+pguid+")";
using (DbDataReader reader = dbCmd2.ExecuteReader())
{
List<object[]> readValuesFromIndex = new List<object[]>();
while (reader.Read())
{
//Point reached
object[] arr = new object[reader.VisibleFieldCount];
reader.GetValues(arr);
//...
}
reader.Close();
}
using (OleDbCommand dbCmd3 = new OleDbCommand { Connection = m_Connection })
{
dbCmd3.CommandText = "SELECT * FROM tbIndex where pguid in (#pguid)";
dbCmd3.Parameters.Add("#pguid", OleDbType.VarChar).Value = pguid;
using (DbDataReader reader = dbCmd3.ExecuteReader())
{
List<object[]> readValuesFromIndex = new List<object[]>();
while (reader.Read())
{
//Point not reached
object[] arr = new object[reader.VisibleFieldCount];
reader.GetValues(arr);
//...
}
reader.Close();
}
}
Note that pguid is set to "'4a651816-e15b-4c6a-85c4-74033ca6c423', '0add7bff-a22f-4238-9c7f-e1ff4ed3c7e2', '742fae8b-2692-4a6f-802c-848fad570696', '5e6b65de-2403-4800-a47d-e57c7bd8e0a6'".
I always thought that the second option would simply replace the parameter in a safe manner but this is obviously not the case.
My question is:
Why doesn't the second option return any values?
A parameter always is a single value.
An in clause requires multiple values, separated by comma's.
You can do something like the following to pass them like separate parameters:
string[] guids = pguid.Split(',');
string sqlin = "";
int paramno = -1;
foreach (var guid in guids)
{
parametercount ++;
sqlin = sqlin + "#Param" + (string)parametercount; + ","
}
dbCmd3.CommandText = "SELECT * FROM tbIndex where pguid in (" + sqlin.Substring(0, sqlin.Length-1) + ")";
for(int i = 0; i <= parametercount; i++){
dbCmd3.Parameters.Add("#Param" + (string)i, OleDbType.VarChar).Value = guids[i].Replace("'", "");
}

Can a C# SQL Parameter Contain '='

So I am trying to create parameters to pass to my query and was wondering if I could pass a parameter that contains an '=' sign in it that replaces the traditional '=' sign in the SQL statement. It would be like the following:
string aoi = "=" + comboBox1.Text;
string comp = "=" + comboBox2.Text;
//Default values of their respective Combo Boxes.
if(aoi == "Area Of Interest")
aoi = "!= NULL";
if (comp == "Company")
comp = "!= NULL";
cmd.CommandText = "SELECT * FROM JobListInfo" +
"WHERE AreaOfInterest #AOI AND Company #Company";
cmd.Parameters.AddWithValue("#AOI", aoi);
cmd.Parameters.AddWithValue("#Company", comp);
The reason I am asking is because if the user doesn't change the default value, I want it to pull all the records (with respect to the rest of the SQL statement). I understand I could create an OR statement, but I have three other parameters I would like to pass as well and didn't want to create 15 OR cases.
EDIT: I found a solution to my problem. I changed the '=' to Like and changed the strings to '%' if they didn't select a value. This shouldn't cause any SQL injection issues, right?
Sample Code:
if(aoi == "Area of Interest")
aoi = "%"
cmd.CommandText = "SELECT * FROM JobListInfo " +
"WHERE AreaOfInterest LIKE #AOI";
cmd.Parameters.AddWithValue("#AOI", aoi);
Not via a parameter. If this were allowed, it would potentially introduce SQL injection vulnerabilities.
A potential solution would be to dynamically create the CommandText string by appending database column names and parameter placeholders to the query's WHERE clause.
WARNING: Do not append input values to the WHERE clause of your query string! This will leave you vulnerable to SQL injection. Instead, append parameter placeholders and then populate them using the cmd.Parameters.AddWithValue() method.
That being said, something like the code below might work. However, it would depend on you selecting a single default value for your combo-boxes. Consequently, you would need to use UI labels instead of default values to describe the combo-boxes in your app.
string MY_DEFAULT_VALUE = 'Pick One:';
string queryString = "SELECT * FROM my_table";
//Populate Dictionary:
Dictionary<string,ComboBox > columnDictionary= new Dictionary<string, ComboBox>();
columnDictionary.Add("COL_A", comboBox1);
columnDictionary.Add("COL_B", comboBox2);
columnDictionary.Add("COL_C", comboBox3);
//etc...
List<KeyValuePair<string, ComboBox>> appendedColumns = new List<KeyValuePair<string, ComboBox>>();
foreach (KeyValuePair<string, ComboBox> entry in columnDictionary)
{
if (!String.Equals(entry.Value.Text, MY_DEFAULT_VALUE, StringComparison.OrdinalIgnoreCase))
{
string currentColumnName = entry.Key;
string currentColumnParameter = "#" + entry.Key;
if (appendedColumns.Count>1)
{
queryString += " AND ";
}
else
{
queryString += " WHERE ";
}
queryString += currentColumnName + " = " + currentColumnParameter;
appendedColumns.Add(entry);
}
}
cmd.CommandText = queryString;
if (appendedColumns.Count > 0)
{
foreach (KeyValuePair<string, ComboBox> entry in appendedColumns)
{
string currentColumnParameter = "#" + entry.Key;
string currentParameterValue = entry.Value.Text;
cmd.Parameters.AddWithValue(currentColumnParameter, currentParameterValue);
}
}
//Continue on your way...
Short answer to your question is, you cannot use '=' as you have shown. So change your code like this;
string aoi = comboBox1.Text;
string comp = comboBox2.Text;
string sql;
if (aoi == "Area Of Interest" && comp == "Company")
{
sql = #"SELECT * FROM JobListInfo WHERE AreaOfInterest Is Not NULL AND Company Is Not NULL";
}
else if(....)
{
sql =............................
}
else
{
sql = #"SELECT * FROM JobListIn WHERE AreaOfInterest = #AOI AND Company = #Company";
}
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#AOI", aoi);
cmd.Parameters.AddWithValue("#Company", comp);

How to retrieve all fields for a given record using OracleDataReader?

My question, which is similar to this one, is how can I use OracleDataReader to retrieve all the fields for a given record? Currently, I've been using this method, which returns only one column value at a time:
public string Select_File(string filename, string subdirectory, string envID)
{
Data_Access da = new Data_Access();
OracleConnection conn = da.openDB();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM EIP_Deployment_Files"
+ " WHERE Filename ='" + filename + "'"
+ " AND Subdirectory = '" + subdirectory + "'"
+ " AND Environment_ID = '" + envID + "'";
cmd.CommandType = CommandType.Text;
string x;
OracleDataReader dr = cmd.ExecuteReader();
if (dr.HasRows) // file exists in DB
{
dr.Read();
x = dr.GetString(2).ToString(); // return baseline filename (index 2)
}
else
{
x = "New File";
}
cmd.Dispose();
da.CloseDB(conn);
return x;
}
I'm sure that this method is far from perfect and ppl will be quick to point that out (I was basically given it by my supervisor since I didn't have any prior experience in ASP.NET) but all I really care about is that it works. My question is: how can it be modified to return all the fields for a given record?
The fields will be of either VARCHAR2, CHAR, or DATE datatypes, (if that makes a difference) and some of these values may be null. I'm thinking I could convert them to strings and return them as a list?
if u want something like this:
List<User> lstUser = new List<User>();
string sqlQuery = "Select * from User_T where User_Name='" + oUser.UserName + "' And Password='" +oUser.Password + "' AND IsActive='"+1+"' AND IsDelete='"+0+"'";
string connectionString = "Data Source=ORCL;User Id=ACCOUNTS;Password=ACCOUNTS";
using (DBManager dbManager = new DBManager(connectionString))
{
try
{
dbManager.Open();
OracleDataReader dataReader = dbManager.ExecuteDataReader(sqlQuery);
while (dataReader.Read())
{
oUser = new User();
oUser.Id = Convert.ToInt32(dataReader["ID"]);
oUser.CompanyId = Convert.ToInt32(dataReader["Company_ID"]);
oUser.BranchId = Convert.ToInt32(dataReader["Branch_ID"]);
oUser.UserName = Convert.ToString(dataReader["User_Name"]);
lstUser.Add(oUser);
}
dataReader.Close();
dataReader.Dispose();
}
catch
(Exception)
{
}
finally
{
dbManager.Close();
dbManager.Dispose();
}
To read all the data from the columns of the current row in a DataReader, you can simply use GetValues(), and extract the values from the array - they will be Objects, of database types.
Object[] values;
int numColumns = dr.GetValues(values); //after "reading" a row
for (int i = 0; i < numColumns; i++) {
//read values[i]
}
MSDN - "For most applications, the GetValues method provides an efficient means for retrieving all columns, rather than retrieving each column individually."
Sorry for posting an answer to a very old question. As none of the answers are correct (either they have security issues or not checking for DBNull), I have decided to post my own.
public async Task<StringBuilder> FetchFileDetailsAsync(string filename, string subdirectory, string envId)
{
var sb = new StringBuilder();
//TODO: Check the parameters
const string connectionString = "user id=userid;password=secret;data source=" +
"(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=10.0.0.8)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=xe)))";
const string selectQuery = "SELECT * FROM EIP_Deployment_Files"
+ " WHERE Filename = :filename"
+ " AND Subdirectory = :subdirectory"
+ " AND Environment_ID = :envID"
+ " AND rownum<=1";
using (var connection = new OracleConnection(connectionString))
using (var cmd = new OracleCommand(selectQuery, connection) {BindByName = true, FetchSize = 1 /*As we are expecting only one record*/})
{
cmd.Parameters.Add(":filename", OracleDbType.Varchar2).Value = filename;
cmd.Parameters.Add(":subdirectory", OracleDbType.Varchar2).Value = subdirectory;
cmd.Parameters.Add(":envID", OracleDbType.Varchar2).Value = envId;
//TODO: Add Exception Handling
await connection.OpenAsync();
var dataReader = await cmd.ExecuteReaderAsync(CommandBehavior.CloseConnection);
var rowValues = new object[dataReader.FieldCount];
if (dataReader.Read())
{
dataReader.GetValues(rowValues);
for (var keyValueCounter = 0; keyValueCounter < rowValues.Length; keyValueCounter++)
{
sb.AppendFormat("{0}:{1}", dataReader.GetName(keyValueCounter),
rowValues[keyValueCounter] is DBNull ? string.Empty : rowValues[keyValueCounter])
.AppendLine();
}
}
else
{
//No records found, do something here
}
dataReader.Close();
dataReader.Dispose();
}
return sb;
}

problem with multiple search keywords

i have web-application, in the application a user can search by using a single keyword or multiple keyword. i have used every technique but i do not know what is wrong with this code as it do not filter the result and continue adding new result.
the search keywords are seperated by comma, like summer,38,blue these are 3 keywords. the code and structure of the table is give below.
publi override list<result> retrunsearch(string search)
{
string[] search = pQuery.Split(',');
List <result> myresult = new List<result>();
for (int i = 1; i < search.Length; i++)
{
where += " And '%" + search[i] + "%'";
OleDbCommand sqlcmdCommand0 = new OleDbCommand("select Distinct name from table1 where search like '%" + search[0] + "%' " + where + " order by name", sqlcon);
sqlcmdCommand0.CommandType = CommandType.Text;
OleDbDataReader sdaResult0 = sqlcmdCommand0.ExecuteReader();
while (sdaResult0.Read())
{
result restult1= new result();
result1.name = sdaResult0.String(0);
myresult.add(result1);
}
sdaResult0.Close();
}
return myresult;
}
public class result{
public result()
{
}
public string name{get;set;}
}
the structure of the table is:
id name keyword;
1 blue jeans blue;
2 blue jeans 38;
3 blue jeans summer;
4 black jeans black;
5 black jeans 38;
6 black jeans summer;
You are executing a new SELECT statement for each item in the keyword list. Instead, try building the where clause and then executing the select statement:
public override list<result> retrunsearch(string search)
{
string[] search = pQuery.Split(',');
List <result> myresult = new List<result>();
// Build WHERE
for (int i = 1; i < search.Length; i++)
where += " And '%" + search[i] + "%'";
// Now search
OleDbCommand sqlcmdCommand0 = new OleDbCommand("select Distinct name from table1 where search like '%" + search[0] + "%' " + where + " order by name", sqlcon);
sqlcmdCommand0.CommandType = CommandType.Text;
OleDbDataReader sdaResult0 = sqlcmdCommand0.ExecuteReader();
while (sdaResult0.Read())
{
result restult1= new result();
result1.name = sdaResult0.String(0);
result.add(result1);
}
sdaResult0.Close();
return result;
}
A couple of quick notes:
I'm lazy, so I preserved errors in your code such as not declaring the "where" variable.
You might need to use "OR" instead of "AND" in your WHERE clause, depending on how you want your search to work.
The approach you are taking is subject to a SQL injection attack.
You need to refactor your method a bit. Only the query appending should be in the for loop:
public override list<result> retrunsearch(string search)
{
string[] search = pQuery.Split(',');
List <result> myresult = new List<result>();
OleDbCommand cmd = new OleDbCommand("select Distinct name from table1 where search like '%" + search[0] + "%', sqlcon);
cmd.CommandType = CommandType.Text;
for (int i = 1; i < search.Length; i++)
{
cmd.CommandText += " AND search like '%" + search[i] + "%'";
}
cmd.CommandText += " order by name";
OleDbDataReader sdaResult0 = cmd.ExecuteReader();
while (sdaResult0.Read())
{
result restult1= new result();
result1.name = sdaResult0.String(0);
myresult.add(result1);
}
sdaResult0.Close();
return myresult;
}
Second go at retrieving records using one or more keywords. I've added some nicer variable names and formatting along with some syntax tips to help with readability.
public override List<string> Search(string pQuery)
{
string[] keywords = pQuery.Split(',');
List<string> results = new List<string>();
if (keywords.Length == 0)
{
// Code expects at least one keyword - throw exception or return null ?
}
StringBuilder query = new StringBuilder();
query.Append(
string.Format("SELECT DISTINCT name FROM table WHERE keyword LIKE '%{0}%'", keywords[0])
);
// Add extra keywords
if (keywords.Length > 1)
{
for (int i = 1; i < keywords.Length; i++)
{
query.Append(string.Format(" OR keyword LIKE '%{0}%'", keywords[i]));
}
}
// Add order by
query.Append(" ORDER BY name");
using (OleDbCommand command = new OleDbCommand(query.ToString(), sqlcon))
{
command.CommandType = CommandType.Text;
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
results.Add(reader.GetString(0));
}
}
}
return results;
}

Categories

Resources