AllianceMaterials February 2016

access two where parameters command in c#

This is how I did it and I get a data type miss match, but tamp is an integer so I am thinking it is some thing else (I also pass an integer in to tamp at another stage in the program). Do I need to pass it though another int? Or is it a problem with my access statement? The whole block of code worked without the extra where parameter and the for loop.

The for loop help me load them in that order and that is important for what I am doing with it

        for (int i = -100; i < 100; i++)
        {              
            try
            {
                connection.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection = connection;
                string query = "select * from Table1 where Status='" + comboBox5.Text + "'AND Tamp='" + i + "'";
                command.CommandText = query;
                listBox9.Items.Clear();
                OleDbDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {

                    listBox9.Items.Add(reader["Description"].ToString());
                }

                // MessageBox.Show("Data Saved");
                connection.Close();

            }
            catch (Exception ex)
            { MessageBox.Show("error " + ex); }

        }

Answers


Eric J. February 2016

Assuming tamp is defined as an integer in the database, change

"'AND Tamp='" + i + "'";

to

"' AND Tamp=" + i;

By placing the single quotes around it in your SQL command, you are providing a string rather than an integer to your database.

If you are using C# 6 or later, you can use string interpolation to write the string in a clearer manner

$"select * from Table1 where Status='{comboBox5.Text}' AND Tamp={i}"

Note that this is not good practice from a security perspective. You should never take user input and place it directly in your SQL command, as it allows users to provide malicious input that can e.g. delete data or tables. Instead, use parameterized queries. The comic linked in the comments exemplifies this.

Post Status

Asked in February 2016
Viewed 1,820 times
Voted 5
Answered 1 times

Search




Leave an answer