How to search SQL database and display in C# listview - c#

I need to filter an SQL database using C# to display it in a windowsFormsHost.
For that, I created a text box in which you input the required string. Using this input, the code uses the text to search through the database and display on clicking a refresh button.
The refresh button works and is done, I just need to create the list with the selected rows according to my filter.
Here is the code, which states that no value is returned:
private string GetPassengerList(string sPasssenger)
{
string sPasssengerL = textBoxPassengerName.Text;
if (sPasssenger.Trim().Length > 0)
{
string sToTime = dtpToDate.Value.Year.ToString("D4") + #"/" + dtpToDate.Value.Month.ToString("D2") + #"/" + dtpToDate.Value.Day.ToString("D2");
sToTime += #" " + dtpToTime.Value.Hour.ToString("D2") + #":" + dtpToTime.Value.Minute.ToString("D2") + #":" + dtpToTime.Value.Second.ToString("D2");
string sFromTime = dtpFromDate.Value.Year.ToString("D4") + #"/" + dtpFromDate.Value.Month.ToString("D2") + #"/" + dtpFromDate.Value.Day.ToString("D2");
sFromTime += #" " + dtpFromTime.Value.Hour.ToString("D2") + #":" + dtpFromTime.Value.Minute.ToString("D2") + #":" + dtpFromTime.Value.Second.ToString("D2");
string sSqlSelect = #"SELECT Passenger FROM ";
string sSqlWhere = #" WHERE (Created BETWEEN '" + sFromTime + #"' AND '" + sToTime + #"')";// and (IATA='" + sIata + #"')";
string sSqlLike = #" LIKE '%" + sPasssengerL + "'%";
SqlDataReader sqlReader = null;
try {
SqlCommand sqlCommand = new SqlCommand(sSqlSelect + #"dbo.BagData" + sSqlWhere + sSqlLike, this.dbConnection);
sqlReader = sqlCommand.ExecuteReader();
if(!sqlReader.Read()) {
sqlReader.Close();
sqlCommand.CommandText = sSqlSelect + #"dbo.BagDataHistory" + sSqlWhere + sSqlLike;
sqlReader = sqlCommand.ExecuteReader();
if(!sqlReader.Read()) {
sqlReader.Close();
sqlCommand.CommandText = sSqlSelect + #"dbo.BagDataArchive" + sSqlWhere + sSqlLike;
sqlReader = sqlCommand.ExecuteReader();
if(!sqlReader.Read()) {
sqlReader.Close();
}
}
}
if(!sqlReader.IsClosed) {
sPasssengerL = this.GetSqlDataString(#"Passenger", sqlReader);
sqlReader.Close();
}
}
catch(SqlException x) {
MessageBox.Show(#"GetPassengerName(): SQL Exception: " + x.Message, this.GetHashString("Error"), MessageBoxButton.OK, MessageBoxImage.Error);
}
catch(Exception ex) {
MessageBox.Show(#"GetPassengerName(): General Exception: " + ex.Message, this.GetHashString("Error"), MessageBoxButton.OK, MessageBoxImage.Error);
}
finally {
if(sqlReader != null) {
if(!sqlReader.IsClosed) {
sqlReader.Close();
}
}
}
return sPasssengerL;
}
}

You have a few errors in the code you posted.
Using concatenated strings instead of parameters in your sql query.
Re-declaring a variable with the same name as the functions parameter. You are declaring another passenger variable sPasssengerL needlessly in the function now.
Not returning a string value from the function. Your edited code shows the function returning the seemingly unneeded extra passenger variable sPasssengerL now.
Your LIKE statement did not include which column it is checking
against.
I cleaned up the code a little, leaving the sSqlWhere in case that was oddly delcared outside your example. This also shows how to add the first column of data to a listview as you've requested.
EDIT: Per your comment on the original question I've updated the code
to show your sSqlWhere variable.
private void GetPassengerList()
{
string sPassenger = textBoxPassengerName.Text;
if (sPassenger.Trim().Length > 0)
{
string sToTime = dtpToDate.Value.Year.ToString("D4") + #"/" + dtpToDate.Value.Month.ToString("D2") + #"/" + dtpToDate.Value.Day.ToString("D2");
sToTime += #" " + dtpToTime.Value.Hour.ToString("D2") + #":" + dtpToTime.Value.Minute.ToString("D2") + #":" + dtpToTime.Value.Second.ToString("D2");
string sFromTime = dtpFromDate.Value.Year.ToString("D4") + #"/" + dtpFromDate.Value.Month.ToString("D2") + #"/" + dtpFromDate.Value.Day.ToString("D2");
sFromTime += #" " + dtpFromTime.Value.Hour.ToString("D2") + #":" + dtpFromTime.Value.Minute.ToString("D2") + #":" + dtpFromTime.Value.Second.ToString("D2");
string sSqlSelect = #"SELECT Passenger FROM ";
string sSqlWhere = #" WHERE (Created BETWEEN #startDate AND #endDate)";
// I assume this is looking for passenger. Change appropriately.
string sSqlLike = #"AND Passenger LIKE #name";
string searchTerm = "%" + sPassenger + "%";
SqlDataReader sqlReader = null;
try
{
SqlCommand sqlCommand = new SqlCommand(sSqlSelect + #"dbo.BagData" + sSqlWhere, parentWindow.dbConnection);
sqlReader = sqlCommand.ExecuteReader();
if (!sqlReader.Read())
{
sqlReader.Close();
sqlCommand.CommandText = sSqlSelect + #"dbo.BagDataHistory" + sSqlWhere + sSqlLike;
sqlCommand.Parameters.Add(new SqlParameter("#name", searchTerm));
sqlCommand.Parameters.Add(new SqlParameter("#startDate", sToTime));
sqlCommand.Parameters.Add(new SqlParameter("#endDate", sFromTime));
sqlReader = sqlCommand.ExecuteReader();
if (!sqlReader.Read())
{
sqlReader.Close();
sqlCommand.CommandText = sSqlSelect + #"dbo.BagDataArchive" + sSqlWhere + sSqlLike;
sqlReader = sqlCommand.ExecuteReader();
// This will loop through your returned data and add
// an item to a list view (listView1) for each row.
while (sqlReader.Read())
{
ListViewItem lvItem = new ListViewItem();
lvItem.SubItems[0].Text = sqlReader[0].ToString();
lvItem.SubItems.Add(sqlReader[0].ToString());
listView1.Items.Add(lvItem);
}
sqlReader.Close();
}
}
if (!sqlReader.IsClosed)
{
sPassenger = parentWindow.GetSqlDataString(#"Passenger", sqlReader);
sqlReader.Close();
}
}
catch (SqlException x)
{
MessageBox.Show(#"GetPassengerName(): SQL Exception: " + x.Message, parentWindow.GetHashString("Error"), MessageBoxButton.OK, MessageBoxImage.Error);
}
catch (Exception ex)
{
MessageBox.Show(#"GetPassengerName(): General Exception: " + ex.Message, parentWindow.GetHashString("Error"), MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
if (sqlReader != null)
{
if (!sqlReader.IsClosed)
{
sqlReader.Close();
}
}
}
}
}
NOTE: There are other places this code can be cleaned up and simplified but that is beyond the scope of this question.

Check your variables, you've declared sSqlSelect and sSqlLike but not sSqlWhere which you are using in your queries.

a) your function will not compile:
- Missing ";" in several lines,
- local variable declaration "sPessanger" in line 2 conflicts with parameter name ...
b) you never return a value. At least you need a single "return sPassenger;" somewhere in the code to return the selected value.
c) bad style using sql injection. As already stated in the comments, use parameters in your SQL.
d) as far as i can see, you are selecting only a single value from your resultset, or is the GetSqlDataString function supposed to do the job?

Related

Get all items of listbox by converting it in string values

I have listbox and its items are the selected dates from Calendar control in ASP.net. Now I need to filter them in foreach loop according to whether every single date is present database table or not. And the code for same I used is like as:
foreach (string item in ListBoxSelectedDates.Items)
{
string q = "select count(*) from event_calendar where _date='" + Convert.ToDateTime(item).ToString("yyyy-MM-dd") + "'";
MySqlCommand cmd = new MySqlCommand(q, conn);
conn.Open();
if ((long)(cmd.ExecuteScalar() ?? 0) == 0)
{
strBody += i + ". " + Convert.ToDateTime(item).ToString("dd-MMM-yyyy") + ", " + Convert.ToDateTime(item).DayOfWeek + " : Leave <br>";
i++;
}
else
{
strBody += i + ". " + Convert.ToDateTime(item).ToString("dd-MMM-yyyy") + ", " + Convert.ToDateTime(item).DayOfWeek + " : Holiday <br>";
i++;
}
conn.Close();
}
And getting error at first line of above code is:
Unable to cast object of type 'System.Web.UI.WebControls.ListItem' to
type 'System.String'.
I am not getting proper solution after continuously trying...
foreach (var _iterator in ListBoxSelectedDates.Items) // here "lstDate" is name of your list where you store all date.
{
string item = _iterator.ToString();
string q = "select count(*) from event_calendar where _date='" + Convert.ToDateTime(item).ToString("yyyy-MM-dd") + "'";
MySqlCommand cmd = new MySqlCommand(q, conn);
conn.Open();
if ((long)(cmd.ExecuteScalar() ?? 0) == 0)
{
strBody += i + ". " + Convert.ToDateTime(item).ToString("dd-MMM-yyyy") + ", " + Convert.ToDateTime(item).DayOfWeek + " : Leave <br>";
i++;
}
else
{
strBody += i + ". " + Convert.ToDateTime(item).ToString("dd-MMM-yyyy") + ", " + Convert.ToDateTime(item).DayOfWeek + " : Holiday <br>";
i++;
}
conn.Close();
}
You can use the ListItem.ToString() Method to convert the ListItem to a String.
foreach (var _iterator in ListBoxSelectedDates.Items)
{
string item = _iterator.ToString();
//The rest of your logic here
conn.Close();
}
If you want to access explicitly the value, you can have a look to the ListItem documentation, there you can see that there is a public property called Value so you can use instead:
string item = _iterator.Value;
so you get:
foreach (ListItem _iterator in ListBoxSelectedDates.Items)
{
string item = _iterator.Value;
//The rest of your logic here
conn.Close();
}

Datareader Exception Thrown Database - DateTime

In my Access database I have an AutditLog table which Looks like this
I simply want to access this table and display each bit of information when Created*(which is the date of the logs) is equal to today's date.
this is my code
private void ITemail()
{
string FinEmail;
clsDBConnector dbConnector = new clsDBConnector();
OleDbDataReader dr;
dbConnector.Connect();
var sqlStr = " SELECT Created, [Action], ConnectionLoc, ConnectionSystem, Resource, [Text], RecordId, ToVal, ClientName"
+ "FROM tblAudit WHERE (ClientName = '" + Client + "') AND 'Created' = '" + ToDate() + "'";
dr = dbConnector.DoSQL(sqlStr);
while (dr.Read())
{
txtIT.Text = dr[0].ToString() + dr[1].ToString() + dr[2].ToString() + dr[3].ToString() + dr[4].ToString() + dr[5].ToString() + dr[6].ToString()
+ dr[7].ToString() + dr[8].ToString();
}
}
private string ToDate()
{
return DateTime.Today.ToString("dd/MM/yyyy");
}
the problem is that nothing is returned even when i try in server explorer with the correct date as a string nothing is returned. When it reaches the While loop this exception is thrown:
Any help would be very much appreciated
Your date format and the date delimiter is incorrect and spaces are missing:
private void ITemail()
{
string FinEmail;
clsDBConnector dbConnector = new clsDBConnector();
OleDbDataReader dr;
dbConnector.Connect();
var sqlStr = "SELECT Created, [Action], ConnectionLoc, ConnectionSystem, Resource, [Text], RecordId, ToVal, ClientName "
+ "FROM tblAudit WHERE (ClientName = '" + Client + "') AND Created = #" + ToDate() + "#";
dr = dbConnector.DoSQL(sqlStr);
while (dr.Read())
{
txtIT.Text = dr[0].ToString() + dr[1].ToString() + dr[2].ToString() + dr[3].ToString() + dr[4].ToString() + dr[5].ToString() + dr[6].ToString()
+ dr[7].ToString() + dr[8].ToString();
}
}
private string ToDate()
{
return DateTime.Today.ToString("yyyy'/'MM'/'dd");
}

SqlDataReader returns x rows but SQL query returns y rows

First time post as I'm a bit stuck here.
I am using this code to return some rows from a SQL Server database:
public static SqlDataReader SQLSelect(string sqlcommand, string[,] parameters, int length)
{
try
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
conn.Open();
SqlDataReader reader;
SqlCommand cmd = new SqlCommand(sqlcommand, conn);
var allLength = parameters.Length;
for (int i = 0; i < parameters.Length - length; i++)
{
string paramid = parameters[i, 0];
if (paramid == "#date" || paramid == "#Date" || paramid == "#DATE")
{
string paramvalue = parameters[i, 1];
DateTime date = Convert.ToDateTime(paramvalue);
paramvalue = date.ToString("yyyy-MM-dd HH':'mm':'ss");
cmd.Parameters.Add(new SqlParameter(paramid, paramvalue));
}
else
{
string paramvalue = parameters[i, 1];
cmd.Parameters.Add(new SqlParameter(paramid, paramvalue));
}
}
cmd.CommandType = CommandType.StoredProcedure;
reader = cmd.ExecuteReader();
return reader;
}
catch
{
return null;
}
}
This function is called like so
string[,] parameters = new string[1, 2] { { "#studentid", studentid } };
SqlDataReader reader = Common.SQLSelect(Common.tblstudentprogressselectforprinting, parameters, 1);
now all runs fine except the reader only contains 13 rows of data where as the actual query being
exec sp_tblstudentprogress_selectforprinting #studentid=N'87'
as an example, returns 91 rows.
I'm at a loss as to why this is the case. Only thing I have noticed is when using SQL Server profiler, running the query from SQL Server, there is a RPC: Started and Completed, as for running from withing my web app, there is only an RPC: Started.
Any thoughts on this?
EDIT:
here is how I enumerate the reader
protected void btnPrint_Click(object sender, EventArgs e)
{
string[,] parameters = new string[1, 2] { { "#studentid", studentid } };
SqlDataReader reader = Common.SQLSelect(Common.tblstudentprogressselectforprinting, parameters, 1);
string firstname = txtFirstName.Text;
string lastname = txtLastName.Text;
int i=0;
string[] heading1 = new string[reader.FieldCount];
string[] heading2 = new string[reader.FieldCount];
string[] log = new string[reader.FieldCount];
try
{
while (reader.Read())
{
heading1[i] = "Progress Log for: Block: " + reader["block"].ToString() + " Lesson: " + reader["lesson"].ToString();
heading2[i] = "";
log[i] =
/*"PROGRESS LOG for " + reader["firstname"].ToString() + " " + reader["lastname"].ToString() + " Printed on " + DateTime.Today.ToShortDateString() + Environment.NewLine +*/
Environment.NewLine +
"Teacher: " + reader["teacher"].ToString() + Environment.NewLine +
"Date: " + reader["date"].ToString() + Environment.NewLine +
"Year: " + reader["year"].ToString() + Environment.NewLine +
"Block: " + reader["block"].ToString() + Environment.NewLine +
"Lesson: " + reader["lesson"].ToString() + Environment.NewLine +
"Warm Up: " + reader["warmup"].ToString() + Environment.NewLine +
"Range: " + reader["range"].ToString() + Environment.NewLine +
"Technique Sheet: " + reader["techniquesheet"].ToString() + Environment.NewLine +
"Technique Other: " + reader["techniqueother"].ToString() + Environment.NewLine +
Environment.NewLine +
"Notes: " + reader["notes"].ToString() + Environment.NewLine +
Environment.NewLine +
"Mark: " + reader["mark"].ToString()+ Environment.NewLine ;
i++;
}
}
catch
{
}
finally
{
if (Common.conn != null)
{
Common.conn.Close();
}
}
Common.PDFCreateProgressLog("Progress log for: " + firstname + " " + lastname, "Progress log for: " + firstname + " " + lastname, "PDF_" + firstname + " " + lastname + "-" + DateTime.Today.ToString("yyyy-MM-dd") + ".pdf", "Progress log for: " + firstname + " " + lastname, log, heading1, heading2);
}
You are confusing the meaning of the FieldCount property. It identifies the number of Columns, not the number of Rows. You cannot determine the total number of rows from a streaming source like a Reader, without enumerating all of the rows first (at least once, anyway).
So you will need to extend your arrays each time (lists might be easier for this) you read a row from the Reader and test the Reader to se when there are no more rows.

SqlCommand AddWithValue and if statements issue with gridview

I am trying to build a web form that uses SQL queries to help populate various dropdowns and display results in gridviews, the issue i'm having at the moment is getting the user input to replace varibles in the SQL query.
My query is as follows:
SELECT TOP 50
'Select' AS 'Select',
id_ref AS 'Number',
created_date AS 'Date Created',
address 'Address',
category AS 'Category',
borough
FROM Events
WHERE location_address LIKE '%%'
AND borough #borcond
AND admin_ref #stacond
AND id_ref #Numcond
AND category #cat
AND created_date #startDate
AND created_date #endDate
AND address LIKE #Addresscond
ORDER BY id_todays_date DESC
My C# code is as follows:
public void SQLQueryv2(
string AddressSel,
string startDateSel,
string endDateSel,
string incidentSel,
string borsel,
string stasel,
string numsel)
{
//this is filled in really
SqlConnection Connection = new SqlConnection(
"Data Source=;Initial Catalog=;User=;Password=;");
string sqlquery = <<as above>>
try
{
SqlCommand Command = new SqlCommand(sqlquery, Connection);
Connection.Open();
if (borsel == "Select Borough")
{
Command.Parameters.AddWithValue("#borcond", " = IS NOT NULL ");
}
else
{
Command.Parameters.AddWithValue("#borcond","= " + "'" + borsel + "'");
}
if (stasel == "Select Town")
{
Command.Parameters.AddWithValue("#stacond", " = IS NOT NULL ");
}
else
{
Command.Parameters.AddWithValue("#borcond","= "+ "'" + borsel + "'");
}
if (startDateSel == "")
{
Command.Parameters.AddWithValue("#startDate", " = IS NOT NULL");
}
else
{
Command.Parameters.AddWithValue(
"#startDate",
">= CONVERT(datetime," + "'" + startDateSel + "'" + ",103)");
}
if (endDateSel == "")
{
Command.Parameters.AddWithValue("#endDate", " = IS NOT NULL");
}
else
{
Command.Parameters.AddWithValue(
"#endDate",
">= CONVERT(datetime," + "'" + endDateSel + "'" + ",103)");
}
if (incidentSel == "Select Category")
{
Command.Parameters.AddWithValue(
"#cat",
" in ('cat a','cat b','cat c')");
}
else
{
Command.Parameters.AddWithValue(
"#cat",
" AND category =" + "'" + incidentSel + "'");
}
if (AddressSel == "")
{
Command.Parameters.AddWithValue("#Addresscond", "%%");
}
else
{
Command.Parameters.AddWithValue("#Addresscond","%" + AddressSel + "%");
}
if (numsel == "")
{
Command.Parameters.AddWithValue("#Numcond", " = IS NOT NULL ");
}
else
{
Command.Parameters.AddWithValue("#Numcond", "= " + "'" + numsel + "'");
}
//use adapter to populate dataset...
SqlDataAdapter DataAdapter = new SqlDataAdapter(sqlquery, Connection);
DataTable DataTable = new DataTable();
DataAdapter.SelectCommand = Command;
DataAdapter.Fill(DataTable);
//then bind dataset to the gridview
GridView1.AutoGenerateColumns = true;
GridView1.DataSource = DataTable;
GridView1.DataBind();
lblResults.Visible = true;
lblResults.ForeColor = System.Drawing.Color.Green;
lblResults.Text = "Your search has returned "
+ Dataset.Tables[0].Select(
"'Incident Number' IS NOT NULL").Length.ToString()
+ " records.";
}
catch (Exception err)
{
lblResults.Visible = true;
lblResults.ForeColor = System.Drawing.Color.Red;
lblResults.Text =
"An error has occurred loading data into the table view. ";
lblResults.Text += err.Message;
}
}
When run, the Gridview doesn't populate and the query (when investigated) it still has the variables and not the 'is nulls' or user inputs.
I think its something to so with the IF statements but i'm entirely sure. I think i just need another pair of eyes on this, any help would be appreciated.
Bit more info:
If i take out the sqlCommand bits it works perfectly with the IF statements, i'm trying to stop people from using malicious SQL queries.
This really isn't the correct way to use parameters. You should only assign values to them, not add comparison operators. Here's an example of how to "fix" your query for the #borcond parameter
...
AND ((#borcond = 'Select Borough' AND borough IS NOT NULL)
OR borough = #borcond)
...
Note: you don't need the equal sign with IS NOT NULL
And replace the if-else with
Command.Parameters.AddWithValue("#borcond", borsel);
You'll need to do similar changes for all of your parameters. The trick here is to basically move your if-else logic from the code into the sql query.
Additionally I don't think you need the location_address LIKE '%%' in your query as that just matches everything.
What juhar said. You've got the wrong idea about parameters. They're parameters and not text substitution. Here's an example of a valid query:
Select firstname, lastname from contacts
where ssn = #ssn
And in your code you'd say
Command.parameters.AddWithValue("#ssn","123-45-6789")

Code repeating itself causing duplicate records in database

this problem is a bit of a difficult one to explain but here it goes. I have a function which adds a record to a MySQL Database online from a local SQLiteDatabase. A function is first called to retrieve the local data and each line is sent to the upload function which adds the record to the online MySQL Database. When these functions are called from a another function A it works fine but when called from a different function. Function B duplicate records are entered into the database.
During debugging to try and resolve the problem I find that when it is duplicating records it is going to cmd.executeNonQuery() then going to the next couple of line but then for no reason will go back up to cmd.executeNonQuery() therefore duplicating the record. The code is below
private void uploadDatabase(string company, string oldCompany, string companyURL, string loginUsername, string oldUsername, string password, string type, string perform, string direction)
{
Boolean recordFound = false;
recordFound = checkRecordNotExist(company, loginUsername);
MySQLDBWork dbase = new MySQLDBWork();
try
{
dbase.openConnection();
if (perform == "insert" && !recordFound)
{
string query = "INSERT INTO `" + username + "` (pas_company, pas_companyURL, pas_username, pas_password, pas_type) "
+ "VALUES ('" + company + "', '" + companyURL + "', '" + loginUsername + "', '" + password + "', '" + type + "')";
Console.WriteLine("Query: " + query);
MySqlCommand cmd = new MySqlCommand(query, dbase.conn);
cmd.ExecuteNonQuery();
recordFound = true;
query = "";
company = "";
loginUsername = "";
cmd.Dispose();
}
if (perform == "delete")
{
string query = "DELETE FROM `" + username + "` WHERE pas_company='" + company + "' AND pas_username='" + loginUsername + "'";
dbase.performQuery(query);
}
}
catch (MySqlException ex)
{
Console.WriteLine("Adding Online Error: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General Exception: " + ex.Message);
}
finally
{
dbase.closeConnection();
//dbase.conn.Dispose();
company = null;
loginUsername = null;
}
}
The problem is within the if statement perform == "insert" && !recordFound.
I'm not sure if the code above will help to solve the problem but this is the function that is going wrong when called from function b but works fine from function A. Thanks for any help and suggestions you can offer.
then going to the next couple of line
but then for no reason will go back up
to cmd.executeNonQuery()
That sounds like a simple multithreading problem. The function is accessed again from a different thread. So what's happening is that it goes through your check exists in both threads before it is inserted in either, and then it is inserted in both.
So, create a lock, and lock the code... something like this:
private System.Object uploadLock = new System.Object();
private void uploadDatabase(string company, string oldCompany, string companyURL, string loginUsername, string oldUsername, string password, string type, string perform, string direction)
{
lock(uploadLock ) {
Boolean recordFound = false;
recordFound = checkRecordNotExist(company, loginUsername);
MySQLDBWork dbase = new MySQLDBWork();
try
{
dbase.openConnection();
if (perform == "insert" && !recordFound)
{
string query = "INSERT INTO `" + username + "` (pas_company, pas_companyURL, pas_username, pas_password, pas_type) "
+ "VALUES ('" + company + "', '" + companyURL + "', '" + loginUsername + "', '" + password + "', '" + type + "')";
Console.WriteLine("Query: " + query);
MySqlCommand cmd = new MySqlCommand(query, dbase.conn);
cmd.ExecuteNonQuery();
recordFound = true;
query = "";
company = "";
loginUsername = "";
cmd.Dispose();
}
if (perform == "delete")
{
string query = "DELETE FROM `" + username + "` WHERE pas_company='" + company + "' AND pas_username='" + loginUsername + "'";
dbase.performQuery(query);
}
}
catch (MySqlException ex)
{
Console.WriteLine("Adding Online Error: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General Exception: " + ex.Message);
}
finally
{
dbase.closeConnection();
//dbase.conn.Dispose();
company = null;
loginUsername = null;
}
}
}
The lock will allow access to the code to only on thread at a time. So no more duplications.
My advice to you:
Always use transactions and you won't be able make duplications. You also may make LoginName column unique and properly handle db error.
DO NOT concatenate string to build query, please. Use command parameters - simplest way escape SQL injection. Currently you have at least 4 vulnerable parameter. Awesome ;)
I would suggest putting a breakpoint on cmd.ExecuteNonQuery(); and inspecting the call stack each time it is hit, paying special attention to the second/duplicate hit. Also pay attention to which thread the breakpoint is being hit on. Doing these things should point you to the problem.

Categories

Resources