带参数的SqlCommand如何工作?

时间:2016-08-19 20:31:50

标签: c# .net sql-server sqlcommand parameterized-query

public string InsertStudent(Student student)
{
    string message = "";
    SqlConnection connection = new SqlConnection(connectionString);

    string query = "insert into Students values(@regNo, @name, @email, @departmentId)";

    SqlCommand command = new SqlCommand(query, connection);
    command.Parameters.Clear();

    command.Parameters.Add("regNo", SqlDbType.VarChar, 50).Value = student.RegNo;

    //////////////////or//////////////
    command.Parameters.Add("name", SqlDbType.VarChar);
    command.Parameters["name"].Value = student.Name;

    command.Parameters.Add("email", SqlDbType.VarChar);
    command.Parameters["email"].Value = student.Email;

    command.Parameters.Add("departmentId", SqlDbType.Int);
    command.Parameters["departmentId"].Value = student.DepartmentId;

    connection.Open();
    int rowAffected = command.ExecuteNonQuery();
    connection.Close();
}

我的问题:我写的时候

command.ExecuteNonQuery() 

command.ExecuteReader()

命令参考如何找出新创建的SqlParameter对象的引用或内存位置?

您可以在堆内存和堆栈内存中绘制这些对象的引用及其关系的图片吗?

我的回答可能是以下图片:

enter image description here

2 个答案:

答案 0 :(得分:1)

参数存储在command.Parameters中。该命令使用该集合枚举所有参数并通过线路发送它们。

答案 1 :(得分:-1)

有几种方法。 看到这个链接:

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters(v=vs.110).aspx

以下示例演示了如何创建SqlCommand并添加参数:

private static void UpdateDemographics(Int32 customerID,
    string demoXml, string connectionString)
{
    // Update the demographics for a store, which is stored 
    // in an xml column. 
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@ID", SqlDbType.Int);
        command.Parameters["@ID"].Value = customerID;

        // Use AddWithValue to assign Demographics.
        // SQL Server will implicitly convert strings into XML.
        command.Parameters.AddWithValue("@demographics", demoXml);

        try
        {
            connection.Open();
            Int32 rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine("RowsAffected: {0}", rowsAffected);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}