Search code examples
c#selectoledboledbconnectionoledbdataadapter

Select statement ignoring parameters?


When I use this code it returns every row in the table and i have no idea why.

string SelectOleDb = "SELECT Top 1 * From `Employee Info` Where [Employee Name]=@EmployeeName" Order By ID DESC";

OleDbConnection OleDbCon = new OleDbConnection(EmployeeInfo.Properties.Settings.Default.cstrEmployeeInfoDatabase);
OleDbDataAdapter OleDbAdpt = new OleDbDataAdapter();
OleDbCommand OleDbCom = new OleDbCommand(SelectOleDb, OleDbCon);
OleDbCom.Parameters.AddWithValue("@EmployeeName", employee_NameComboBox.Text);
OleDbAdpt.SelectCommand = OleDbCom;

DataSet FooDS = new DataSet();
OleDbCon.Open();
OleDbAdpt.Fill(FooDS);
OleDbCon.Close();
OleDbCon.Dispose();
DataTable EmployeeInfo = FooDS.Tables[0];

And i even copy pasted a value from the Employee Name column into the text box to verify i was using a valid employee name. I would expect nothing to be returned instead of everything if the statement was incorrect though.

UPDATE: I have also tried removing the Named Paramter "@EmployeeName" and entering a hard corded name surrounded by single quotes. Yet still statement returns every thing in Employee Info


Solution

  • Others have stated that OleDb required a ? and that it did not accept Named Parameters. This is false. I have fixed my code and it is working. The problem at hand was that the Statement required different ways to define spaces.

    With the OleDB connection the Table Name if it had a space had to be in EITHER `(Ticks) or both will work the same.

    The confusions begins when you have Column Names with spaces. When the statement is built All column names have to have an _ (Under Score) in place of the Spaces the column names. While both `(Ticks) and are optional for Column names. All that is REQUIRED is the replacement of " "(Space) with _(under score)

    What adds to the confusion is the fact that the table name is REQUIRED to have either `(Ticks) or and if you do replace a " "(Space) with _(under score) it will not find the table.

    My fixed Code:

            string SelectOleDb = "SELECT Top 1 * From [Employee Info] Where Employee_Name= @EmployeeName Order By ID DESC";
    
            OleDbConnection OleDbCon = new OleDbConnection(EmployeeInfo.Properties.Settings.Default.cstrEmployeeInfoDatabase);
            OleDbDataAdapter OleDbAdpt = new OleDbDataAdapter();
            OleDbCommand OleDbCom = new OleDbCommand(SelectOleDb, OleDbCon);
            OleDbCom.Parameters.AddWithValue("@EmployeeName", employee_NameComboBox.Text);
            OleDbAdpt.SelectCommand = OleDbCom;
    
                DataSet EmployeeInfoDS = new DataSet();
                OleDbCon.Open();
                OleDbAdpt.Fill(EmployeeInfoDS);
                OleDbCon.Close();
                OleDbCon.Dispose();
                DataTable EmployeeInfoDT = EmployeeInfoDS.Tables[0];