在我看来,ADO.Net就这个5个组件;分别是Connection、Parameter、Transaction、Command、DataReader。
IDbConnection cn = null;
IDataParameter para = null;
IDbTransaction tran = null;
IDbCommand cmd = null;
IDataReader dr = null;
try
{
cn = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True");
if (cn.State == ConnectionState.Closed) cn.Open();
//tran = cn.BeginTransaction();
para = new SqlParameter("@Id", SqlDbType.Int, 4);
para.Value = 1;
cmd = new SqlCommand();
cmd.CommandText = "select LastName,FirstName from dbo.Employees where EmployeeID=@Id";
cmd.CommandTimeout = 150;
cmd.CommandType = CommandType.Text;
cmd.Connection = cn;
cmd.Parameters.Add(para);
//cmd.Transaction = tran;
try
{
//cmd.ExecuteNonQuery();
//cmd.ExecuteScalar();
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dr.Read())
{
Console.WriteLine(dr[0].ToString() + @"\" + dr[1].ToString());
}
//tran.Commit();
}
catch (Exception)
{
//tran.Rollback();
throw;
}
}
catch (Exception)
{
throw;
}
finally
{
if (cn.State == ConnectionState.Open)
{
cn.Close();
dr.Close();
}
if (cn != null) cn.Dispose();
if (cmd != null) cmd.Dispose();
if (para != null) para = null;
if (tran != null) tran.Dispose();
if (dr != null) dr.Dispose();
}
浙公网安备 33010602011771号