如何在 C# 中使用带有参数化查询的 SqlDataReader?

How to use SqlDataReader with a parametrized query in c#?

我正在查看参数化查询问题 我找不到使用 SqlDataReader 和参数化查询来填充下拉列表的示例。

现在我可以使用我的代码在这里填充我的下拉列表

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

但是,我想使这个 select 语句参数化。我怎样才能做到这一点? 我很乐意编写如下参数化插入语句:

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

那么,我怎样才能使我的第一个查询像第二个示例那样呢?

谢谢

纳姆里克

首先,ExecuteNonQuery() method isn't valid for SELECT query, just stick with ExecuteReader()的用法,因为你要return查询结果。这是ExecuteNonQuery方法的用法说明:

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.

修改后的查询流程应该是这样的:

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
}

如果要对 SELECT 语句使用参数化查询,则至少需要在 WHERE 子句中包含一列(和一个参数名称)(参见下面的示例):

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

然后,您可以使用SqlParameter将参数值传递到上面的查询中:

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
}

注意:避免在使用相同活动连接的SELECT语句填充数据的同时执行INSERT/UPDATE/DELETE操作,在执行另一个查询之前应先关闭先前的连接。

更多示例:

How to use string variable in sql statement

How to use sql parameters for a select query?