SqlCommand.Connection Property
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Gets or sets the SqlConnection used by this instance of the SqlCommand .
public:
property Microsoft::Data::SqlClient::SqlConnection ^ Connection { Microsoft::Data::SqlClient::SqlConnection ^ get(); void set(Microsoft::Data::SqlClient::SqlConnection ^ value); };
public Microsoft.Data.SqlClient.SqlConnection Connection { get; set; }
member this.Connection : Microsoft.Data.SqlClient.SqlConnection with get, set
Public Property Connection As SqlConnection
The connection to a data source. The default value is
null
.
The Connection property was changed while the command was enlisted in a transaction.
The following example creates a SqlCommand and sets some of its properties.
// <Snippet1>
using System;
using System.Data;
using Microsoft.Data.SqlClient;
namespace SqlCommandCS
{
class Program
{
static void Main()
{
string str = "Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=SSPI";
string qs = "SELECT OrderID, CustomerID FROM dbo.Orders;";
CreateCommand(qs, str);
}
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandTimeout = 15;
command.CommandType = CommandType.Text;
command.CommandText = queryString;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
}
// </Snippet1>
}
}
If the command is enlisted in an existing transaction, and the connection is changed, trying to execute the command will throw an InvalidOperationException.
If the Transaction property is not null and the transaction has already been committed or rolled back, Transaction is set to null.
Produkt | Verzie |
---|---|
SqlClient .NET Core | 1.0, 1.1, 2.0, 2.1, 3.0, 3.1, 4.0, 4.1, 5.0, 5.1, 5.2 |
SqlClient .NET Framework | 1.0, 1.1, 2.0, 2.1, 3.0, 3.1, 4.0, 4.1, 5.0, 5.1, 5.2 |
SqlClient .NET Standard | 1.0, 1.1, 2.0, 2.1, 3.0, 3.1, 4.0, 4.1, 5.0, 5.1, 5.2 |