ADO.NET 学习笔记

1、连接到 SQL Server:

   
     
// Assumes connectionString is a valid connection string.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Do work here.
}

 

2、执行命令 (ADO.NET)

 

下面的代码示例演示如何创建 SqlCommand 对象以通过设置其属性执行存储过程。 SqlParameter 对象用于指定存储过程的输入参数。 使用 ExecuteReader 方法执行此命令,并在控制台窗口中显示 SqlDataReader 的输出。

 

代码
    
      
static void GetSalesByCategory( string connectionString, string categoryName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create the command and set its properties.
SqlCommand command = new SqlCommand();
command.Connection
= connection;
command.CommandText
= " SalesByCategory " ;
command.CommandType
= CommandType.StoredProcedure;

// Add the input parameter and set its properties.
SqlParameter parameter = new SqlParameter();
parameter.ParameterName
= " @CategoryName " ;
parameter.SqlDbType
= SqlDbType.NVarChar;
parameter.Direction
= ParameterDirection.Input;
parameter.Value
= categoryName;

// Add the parameter to the Parameters collection.
command.Parameters.Add(parameter);

// Open the connection and execute the reader.
connection.Open();
SqlDataReader reader
= command.ExecuteReader();

if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine(
" {0}: {1:C} " , reader[ 0 ], reader[ 1 ]);
}
}
else
{
Console.WriteLine(
" No rows found. " );
}
reader.Close();
}
}

 

 

你可能感兴趣的:(.net)