problem with multiple search keywords - c#

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

Related

How do I pull data from mysql and assign it to corresponding values

Good Day.
I have a stock list in mysql database
I then have a windows form where i can allocate stock to a certain job, i do this by pulling all from my parts list in mysql and checking if the item selected by the user is in stock, i then add that item to a list using listbox.Items.Add(myitem). In also ass the quantity the user wants to a different list.
When I allocate the stock to a job i create one string separated by ',' and store that to mysql and the same with my quantites resulting is a parts string that looks like: 'PART001,PART002,PART003' and my quantities like: '2,1,3'.
I then add that to a request list which the admin needs to approve.
My problem comes in where the request form is loaded, I pull these parts and quantity lists from mySql and split them wit myString.Split(',');
And I then just add them to another listbox, HOWEVER when i get the quantities that my stock table has available, I loop over the part numbers and pull the quantities but if I for example have my first part as item 3 in my stock table and my second item as my 1st item in my stock list, it will assign item 1's quantity to my item 3. So basically my loop does not assign the right values.
Here is my code for checking the values
ListBox lb = PartsListBox;
ListBox lbq = PartsQuanListBox;
String query = "SELECT * FROM parts WHERE partnum = '"+PartsSelectCb.Text.Trim()+"'";
String partnum = "N/A";
int quan = 0;
MySqlConnection con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
partnum = (String)dr["partnum"];
}
con.Close();
if(PartsSelectCb.Text == partnum)
{
quan = int.Parse(textBox1.Text);
if (quan > 0)
{
if (!lb.Items.Contains(PartsSelectCb.Text.Trim()))
{
lb.Items.Add(PartsSelectCb.Text.Trim());
lbq.Items.Add(textBox1.Text.Trim());
}
}
}
And here is my code for inserting those values into my request table
private void SendRequest()
{
String dte = DateTime.Now.ToShortDateString();
String g = "";
String h = "";
String a = "";
String b = "";
if (PartsListBox.Items.Count > 0)
{
foreach (var item in PartsListBox.Items)
{
g += item.ToString() + ",";
}
h = g.Substring(0, g.Length - 1);
}
if (PartsQuanListBox.Items.Count > 0)
{
foreach (var itemt in PartsQuanListBox.Items)
{
a += itemt.ToString() + ",";
}
b = a.Substring(0, a.Length - 1);
}
String query = "INSERT INTO partsbook VALUES (NULL,'" + h + "','" + b + "','"
+ ReqTxt.Text.Trim() + "','" + userN + "','" + dte + "','" +""+"','"+ "REQUEST" + "')";
MySqlConnection dataCon = new MySqlConnection(conString);
dataCon.Open();
MySqlCommand cmd = new MySqlCommand(query, dataCon);
try
{
cmd.ExecuteNonQuery();
pmf.CheckRequests();
this.Close();
}
catch (Exception r)
{
MessageBox.Show("ERROR :" + r.Message.ToString());
}
dataCon.Close();
MessageBox.Show("REQUEST SENT");
this.Close();
}
Then on the request side
private void GetStock()
{
String query = "SELECT * FROM parts";
String qtys = "";
MySqlConnection con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
String nme = (String)dr["partnum"];
foreach(var item in UPartsListBox.Items)
{
if(item.ToString() == nme)
{
int q = (int)dr["qty"];
qtys += q.ToString() + ",";
}
}
}
con.Close();
string[] words = qtys.Split(',');
foreach(var word in words)
{
if(word != "")
{
SPartsQuanListBox.Items.Add(word);
}
}
}
User Request:
Admin View:
Stock Table:

Executing a query with no search term causes System.StackOverflow Exception in System.Runtime.Serialization.dll

I 'm dealing with a query which results in above mentioned error when called with no or limited search string.
The table is 30k records big and when the query is fired with no search string I would expect the database to return all records and have Visual Studio put them in a table (ASP.net), however, if the query is fired like above the StackOverflow error is returned :(
If I fire the query with a more specific search string the script seems to work normal and results are being returned as expected.
I have been googling and all seems to point to an infinite loop or recursion but returning records make me believe it might be another problem.
The query:
SqlConnection conn = new SqlConnection(_cstring);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
conn.Open();
SqlDataReader dr;
if (mode == "zoek_met_zoekterm")
{
cmd.CommandText = "select W1.id, W1.soort_brief, W1.omschrijving, W1.referentie, W1.url, W1.factuur, W3.naam, W3.klantnummer, W4.omschrijving AS w4_omschr, W4.referentie AS w4_ref, substring(W1.referentie,6,2) as w1_jaar, W1.parent AS w1_parent from brief W1 left join brief W4 on W1.parent = W4.id join klant W3 on W3.klantnummer = W1.klantnummer where W1.referentie in (select referentie from brief where substring(referentie,6,2) = #jaar) and (W3.klantnummer like #zoekterm or W1.referentie like #zoekterm or W1.omschrijving like #zoekterm or W3.naam like #zoekterm or W4.omschrijving like #zoekterm) order by W1.id";
cmd.Parameters.Clear();
cmd.Parameters.Add("#zoekterm", SqlDbType.VarChar).Value = "%" + (string)parameters["zoekterm"] + "%";
string jaar = parameters["jaar"].ToString();
jaar = jaar.Substring(2, 2);
cmd.Parameters.Add("#jaar", SqlDbType.VarChar).Value = jaar;//(Int32)parameters["jaar"];
base.LogQuery(cmd);
dr = cmd.ExecuteReader();
while (dr.Read())
{
CBrief brief = new CBrief();
brief.Id = dr.GetInt32(0);
brief.SoortBrief = (Enums.SoortBrief)dr.GetInt32(1);
brief.Omschrijving = Functies.Decrypt(dr.GetString(2), EncryptData);
brief.Referentie = Functies.Decrypt(dr.GetString(3), EncryptData);
brief.Url = Functies.Decrypt(dr.GetString(4), EncryptData);
brief.Factuur = (Enums.SoortDocument)dr.GetInt32(5);
brief.Klantnummer = dr.GetInt32(7);
if (dr.GetString(2).Length == 0)
{
if (!dr.IsDBNull(9) && !dr.IsDBNull(8))
brief.Omschrijving = dr.GetString(9) + " " + dr.GetString(8);
}
ret_value.Add(brief);
}
dr.Close();
dr.Dispose();
}
And the function that calls the query:
public List<CBrief> GetBriefOverzicht(string zoekterm, int jaar)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("zoekterm", zoekterm);
parameters.Add("jaar", jaar);
if (zoekterm.Length == 0)
{
return _dal.brief_search(parameters, "geen_invoer");
}
return _dal.brief_search(parameters, "zoek_met_zoekterm");
}
And last but not least the function that builds the table to display in the web application:
protected void Bzoeken_Click(object sender, EventArgs e)
{
string zoekterm = TBzoekterm.Text;
DateTime nu = DateTime.Now;
int jaar = nu.Year;
List<CBrief> brieven = br_rbs.GetBriefOverzichtWijzigen(zoekterm);
StringBuilder overzicht = new StringBuilder("<table class=\"tabel-beheer-1\">");
foreach (CBrief b in brieven)
{
List<CBijlage> bijlagen = new List<CBijlage>();
CKlant k = sec.GetKlant(b.Klantnummer);
string klantnaam = k.Naam;
string richting = "";
if (b.OmschrijvingAanwezig == true)
{
bijlagen = br_rbs.GetBijlagenBrieven(b.Id);
}
if (b.SoortBrief == Enums.SoortBrief.Inkomend) richting = "van: "; else richting = "naar: ";
// MG10082017 Ik heb hier twee icoontjes in elkaar geflanst om te testen. Deze moeten nog aangepast worden zodat ze in het geheeel passen.
overzicht.AppendLine("<tr><td><img src=\"/images/bg/document.jpg\" alt=\"open document\"></td><td><img src=\"/images/bg/detail.jpg\" alt=\"details\"></td><td><b>" + b.Referentie + "</b></td><td><i>" + b.SoortBrief.ToString() + " " + richting + "</i> " + klantnaam + "</td><td><b> " + b.Factuur.ToString() + ":</b> " + b.Omschrijving /*+"</td><td>"*/);
if (bijlagen.Count > 0)
{
foreach (CBijlage bijl in bijlagen)
{
overzicht.AppendLine("</br> " + bijl.Naam + "");
}
}
}
overzicht.AppendLine("</td></tr></table>");
Loverzicht.Text = overzicht.ToString();
}
The error usually points to: System.Web.dll or w3wp.exe (when not ran in debug mode). If my assumption is wrong and it seems to be an infinite loop or recursion, how am I going to find this?
The query works flawless in MS-SQL management console.
The Problem is not an infinite loop!
The Problem lies in the UI.
You can't display 30k units at once without a StackOverflow-Exception.
You should call pages of maybe 20 or 30 units at once with an pageIndex.
This way, your application will perform better and avoid such errors.

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

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

Get Names ForEach Checked item in Checkedlistbox

I want to get the names associated with the states i select in my program. Below is the code that i currently have. My database has multiple locations within a state that have different contacts. I just want to select a state and acquire everyone under that state. Thanks for the help!
con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\\Database\\LocNo.accdb");
con.Open();
foreach (Object c in checkedListBox2.CheckedItems)
{
if (checkedListBox2.GetItemCheckState(checkedListBox2.Items.IndexOf(c)) == CheckState.Checked)
{
str1 += c.ToString() + ",";
flag = 1;
}
}
i = 0;
allSelectedtypestring = "";
allSelected = str1.Split(',');
while (allSelected.Length - 1 > i)
{
str = "select c1 from table where state ='" + allSelected[i++] + "'";
cmd = new OleDbCommand(str, con);
dr = cmd.ExecuteReader();
dr.Read();
allSelectedtypestring += dr.GetString(11);
}
label30.Text = Convert.ToString(allSelectedtypestring);
con.Close();
You can use the following code to retrieve the contacts:
var states = new List<string>();
foreach (Object c in checkedListBox2.CheckedItems)
{
states.Add(c.ToString());
flag = 1; // Can also be substituted by states.Count > 0
}
using(var con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\\Database\\LocNo.accdb"))
{
con.Open();
using(var cmd = con.CreateCommand())
{
var paramIndex = 0;
var paramClause = new System.Text.StringBuilder(100);
foreach(var state in states)
{
if (paramClause.Length > 0)
paramClause.Append(", ");
paramClause.Append("?");
var paramName = "State" + (paramIndex++).ToString();
cmd.Parameters.AddWithValue(paramName, state);
}
var paramsClause = string.Join(", ", cmd.Parameters.
cmd.CommandText = "select distinct c1 from table where state IN (" + paramsClause.ToString() + ")";
using(var rdr = cmd.ExecuteReader())
{
var contacts = new List<string>();
while(rdr.Read())
{
contacts.Add(rdr.GetString(0);
}
label30.Text = string.Join(", ", contacts);
}
}
}
Please note that I've made the following changes:
Added using statements to reliably dispose the connection, command and reader.
Used a List<string> as a more convenient way to collect the selected states.
Added DISTINCT to the SELECT in order to filter duplicate entries.
Used a parameter in the command text in order to avoid SQL injection attacks. Though this way to use a parameter with an IN clause works for SQL Server, I haven't checked whether it also works for an Access database. Let me know in the comments if it doesn't work.

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

Categories

Resources