2

I'm looking at parameterized query questions I could not find an example of using SqlDataReader with a parameterized query to populate a drop down list.

Right now I can populate my drop down just fine using my code here

if (!this.IsPostBack)
{
    using (SqlConnection con = new SqlConnection(SQLConnectionString))
    {
        System.Data.SqlClient.SqlCommand go = new System.Data.SqlClient.SqlCommand();

        con.Open();
        go.Connection = con;
        go.CommandText = "SELECT InsuredID, FirstName, LastName FROM [Lab2].[dbo].[INSURED]";
        go.ExecuteNonQuery();

        SqlDataReader readIn = go.ExecuteReader();

        while (readIn.Read())
        {
            ddlHomeInsuredID.Items.Add(
                new ListItem(readIn["InsuredID"].ToString() + " : " + readIn["FirstName"].ToString()
                + " " + readIn["LastName"].ToString()));
        }

        con.Close();

        ddlHomeInsuredID.Items.Insert(0, new ListItem("--Select InsuredID--", "0"));
    }
}

However, I want to make this select statement parameterized. How can I do this? I am comfortable writing parameterized insert statements like the following:

using (SqlConnection connection = new SqlConnection(SQLConnectionString))
{
    SqlCommand command = new SqlCommand();
    command.Connection = connection;
    command.CommandType = System.Data.CommandType.Text;

    command.CommandText = @"INSERT INTO [Lab2].[dbo].[INSURED] ([FirstName], [LastName], [MI], [DateOfBirth], 
[CreditScore], [AddressID], [DriversLicenseNumber], [LastUpdatedBy], [LastUpdated]) VALUES
(@firstName, @lastName, @middleInitial, @dateOfBirth, @creditScore, @addressID,
@driversLicenseNumber, @lastUpdatedBy, @lastUpdated)";

    command.Parameters.Add("@firstName", SqlDbType.VarChar, 20).Value = Insured.insuredArr[j].getFirstName();
    command.Parameters.Add("@lastName", SqlDbType.VarChar, 30).Value = Insured.insuredArr[j].getLastName();
    command.Parameters.Add("@middleInitial", SqlDbType.Char, 1).Value = Insured.insuredArr[j].getMiddleInitial();
    command.Parameters.Add("@dateOfBirth", SqlDbType.VarChar, 30).Value = Insured.insuredArr[j].getDateOfBirth();
    command.Parameters.Add("@creditScore", SqlDbType.Int).Value = Insured.insuredArr[j].getCreditScore();
    command.Parameters.Add("@addressID", SqlDbType.Int).Value = Insured.insuredArr[j].getAddressID();
    command.Parameters.Add("@driversLicenseNumber", SqlDbType.VarChar, 30).Value = Insured.insuredArr[j].getDriversLicenseNumber();
    command.Parameters.Add("@lastUpdatedBy", SqlDbType.VarChar, 20).Value = Insured.insuredArr[j].getLastUpdatedBy();
    command.Parameters.Add("@lastUpdated", SqlDbType.Date).Value = Insured.insuredArr[j].getLastUpdated();

    connection.Open();
    command.ExecuteNonQuery();
    connection.Close();
}

MsgBox("Record(s) inserted into database", this.Page, this);

So, how can I make my first query like the second example?

Thanks

nammrick

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
nammrick
  • 99
  • 1
  • 2
  • 8
  • I'm not sure but I could probabky work it out by googling... are you sure you should have `go.ExecuteNonQuery();` line in there - I don't think it's doing anything in this case. – Nick.Mc Oct 05 '17 at 03:15
  • Here's an example under "Execute SQL Query with Filter Condition": https://www.aspsnippets.com/Articles/Parameterized-Queries-ADO.Net.aspx – Nick.Mc Oct 05 '17 at 03:16
  • Yeah that executes the select statement – nammrick Oct 05 '17 at 03:17
  • ... so does `go.ExecuteReader();` on the next line right? Why execute it twice? – Nick.Mc Oct 05 '17 at 03:18
  • 1
    `ExecuteNonQuery` is not meant to execute a select statement. Otherwise, you'd actually be doing a query. It's for a statement which output you don't care about. – Tipx Oct 05 '17 at 03:18
  • You can use parameterized query in `SELECT` statements if containing `WHERE` conditional clause, e.g. `SELECT InsuredID, FirstName, LastName FROM [Lab2].[dbo].[INSURED] WHERE InsuredID = @InsuredID`. From your example, the `WHERE` clause is not exist & the query string just fine, but you need to remove `go.ExecuteNonQuery();` when using `SELECT` (it uses `go.ExecuteReader()` only). – Tetsuya Yamamoto Oct 05 '17 at 03:23
  • how come you are using insert query in second example and at same time you want to populate data into list! – Saif Oct 05 '17 at 03:35

1 Answers1

10

First of all, the usage of ExecuteNonQuery() method isn't valid for SELECT query, just stick with ExecuteReader() since you want to return query results. This is the usage description of ExecuteNonQuery method:

You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.

The modified query flow should be like this:

using (SqlConnection con = new SqlConnection(SQLConnectionString))
{
    SqlCommand go = new SqlCommand();

    con.Open();
    go.Connection = con;
    go.CommandText = "SELECT InsuredID, FirstName, LastName FROM [Lab2].[dbo].[INSURED]";

    SqlDataReader readIn = go.ExecuteReader();
    while (readIn.Read())
    {
       // reading data from reader
    }

    con.Close();

    // other stuff
}

If you want to use parameterized query for SELECT statement, you need at least one column (and one parameter name) to be included in WHERE clause (see example below):

SELECT InsuredID, FirstName, LastName FROM [Lab2].[dbo].[INSURED] WHERE InsuredID = @InsuredID

Then, you can use SqlParameter to pass parameter value into the query above:

using (SqlConnection con = new SqlConnection(SQLConnectionString))
{
    System.Data.SqlClient.SqlCommand go = new System.Data.SqlClient.SqlCommand();

    con.Open();
    go.Connection = con;
    go.CommandText = "SELECT InsuredID, FirstName, LastName FROM [Lab2].[dbo].[INSURED] WHERE InsuredID = @InsuredID";
    go.Parameters.Add("@InsuredID", SqlDbType.Int).Value = 1; // example value for parameter passing

    SqlDataReader readIn = go.ExecuteReader();
    while (readIn.Read())
    {
       // reading data from reader
    }

    con.Close();

    // other stuff
}

NB: Avoid perform INSERT/UPDATE/DELETE operation at the same time with populating data by SELECT statement with same active connection, the previous connection should be closed first before executing another query.

More examples:

How to use string variable in sql statement

How to use sql parameters for a select query?

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
  • 1
    No need to call `con.Close()` as the `using` statement will take care of closing for you. See https://stackoverflow.com/a/18588084/4762482 – taylorswiftfan Mar 28 '20 at 02:58