0% found this document useful (0 votes)
11 views20 pages

Lecture 10 - ADO - NET (Part 1)

Uploaded by

ahihihi.0602
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views20 pages

Lecture 10 - ADO - NET (Part 1)

Uploaded by

ahihihi.0602
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

C# 6 and the .NET 4.

6 Framework

Chapter 21 - ADO.NET Part I: The


Connected Layer
Outline
The Three Faces of ADO.NET
• You can use the ADO.NET libraries in three
conceptually unique manners:
– connected,
– disconnected,
– or through an ORM, such as Entity Framework
Understanding ADO.NET Data
Providers
The Types of the System.Data
Namespace
The Role of the IDbConnection
Interface
namespace System.Data
{
public interface IDbConnection : IDisposable
{
// Properties
string ConnectionString { get; set; }
int ConnectionTimeout { get;}

string Database {get;}

ConnectionState State { get;}


// Methods
IDbTransaction BeginTransaction (IsolationLevel il);
IDbTransaction BeginTransaction ();
void ChangeDatabase (string databaseName);
void Close ();
IDbCommand CreateCommand ();
void Open ();
}
}
The Role of the IDbTransaction
Interface
namespace System.Data
{
public interface IDbTransaction : IDisposable
// Properties
IDbConnection Connection {
get;
}
IsolationLevel IsolationLevel {
get;
}

// Methods
void Commit ();
void Rollback ();
}
}
The Role of the IDCommand Interface
namespace System.Data
{
public interface IDbCommand : IDisposable
{
// Properties
string CommandText {get; set;}
int CommandTimeout {get; set;}
CommandType CommandType {get; set;}
IDbConnection Connection {get; set;}
IDataParameterCollection Parameters {get; }
IDbTransaction Transaction {get; set;}
UpdateRowSource UpdatedRowSource {get; set;}

// Methods
void Cancel ();
IDbDataParameter CreateParameter ();
int ExecuteNonQuery ();
IDataReader ExecuteReader ();
IDataReader ExecuteReader (CommandBehavior behavior);
object ExecuteScalar ();
void Prepare ();
}
}
The Role of the IDbDataParameter and
IDataParameter Interfaces
namespace System.Data
{
public interface IDbDataParameter : IDataParameter
{
// Properties
byte Precision {get; set;}
These allow you to represent parameters
byte Scale {get; set;} within a SQL command (including stored
int Size {get; set;} procedures) through specific ADO.NET
}
}
parameter objects, rather than through
namespace System.Data hard-coded string literals.
{
public interface IDataParameter
{
// Properties
DbType DbType { get; set;}
ParameterDirection Direction { get; set;}
bool IsNullable { get; }
string ParameterName { get; set;}
string SourceColumn { get; set;}
DataRowVersion SourceVersion { get; set;}
object Value { get; set;}
}
}
The Role of the IDbDataAdapter and
IDataAdapter Interfaces
namespace System.Data
{
public interface IDbDataAdapter : IDataAdapter
{
// Properties
IDbCommand DeleteCommand { get; set;}
IDbCommand InsertCommand { get; set;}
You use data adapters to push and pull
IDbCommand SelectCommand { get; set;} DataSets to and from a given data store.
IDbCommand UpdateCommand { get; set;}
}
}
namespace System.Data
{
public interface IDataAdapter
{
// Properties
MissingMappingAction MissingMappingAction { get; set;}
MissingSchemaAction MissingSchemaAction { get; set;}
ITableMappingCollection TableMappings { get; }
// Methods
int Fill (DataSet dataSet);
DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType);
IDataParameter[] GetFillParameters ();
int Update (DataSet dataSet);
}
}
The Role of the IDataReader Interface
public interface IDataReader : IDisposable, IDataRecord
{
int Depth { get; }
bool IsClosed { get; }
int RecordsAffected { get; }

void Close();
DataTable GetSchemaTable();
bool NextResult();
bool Read();
}
The Role of the IDataRecord Interface
public interface IDataRecord
{
int FieldCount { get; }
object this[int i] { get; }
object this[string name] { get; }
string GetName(int i);
string GetDataTypeName(int i);
Type GetFieldType(int i);
object GetValue(int i);
int GetValues(object[] values);
int GetOrdinal(string name);
bool GetBoolean(int i);
byte GetByte(int i);
long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length);
char GetChar(int i);
long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length);
Guid GetGuid(int i);
short GetInt16(int i);
int GetInt32(int i);
long GetInt64(int i);
float GetFloat(int i);
double GetDouble(int i);
string GetString(int i);
Decimal GetDecimal(int i);
DateTime GetDateTime(int i);
IDataReader GetData(int i);
bool IsDBNull(int i);
}
System.Data.Common namespace
• DbCommand:
– The abstract base class for all command classes
• DbConnection:
– The abstract base class for all connection classes
• DbDataAdapter:
– The abstract base class for all data adapter classes
• DbDataReader:
– The abstract base class for all data reader classes
• DbParameter:
– The abstract base class for all parameter classes
• DbTransaction:
– The abstract base class for all transaction classes
The ADO.NET Data Provider Factory
Model
namespace System.Data.Common
{
public abstract class DbProviderFactory
{
// Properties
public virtual bool CanCreateDataSourceEnumerator{get;}
// Constructors
protected DbProviderFactory();
// Methods
public virtual DbCommand CreateCommand();
public virtual DbCommandBuilder CreateCommandBuilder();
public virtual DbConnection CreateConnection();
public virtual DbConnectionStringBuilder CreateConnectionStringBuilder();
public virtual DbDataAdapter CreateDataAdapter();
public virtual DbDataSourceEnumerator CreateDataSourceEnumerator();
public virtual DbParameter CreateParameter();
public virtual CodeAccessPermission CreatePermission(PermissionState state);
}
}

// Get the factory for the SQL data provider.
DbProviderFactory sqlFactory =
DbProviderFactories.GetFactory("System.Data.SqlClient");
...
Creating the database AutoLot
create database AutoLot;
use AutoLot;
create table Inventory(
CarId int auto_increment primary key,
Make nvarchar(50),
Color nvarchar(50),
PetName nvarchar(50)
);
insert into Inventory(Make, Color, PetName) values
('VW', 'Black', 'Zippy'),
('Ford', 'Rust', 'Rusty'),
('Saab', 'Black', 'Mel'),
('Yogo', 'Yellow', 'Clunker'),
('BMW', 'Black', 'Bimmer'),
('BMV', 'Green', 'Hank'),
('BMV', 'Pink', 'Pinky');
Creating the database AutoLot
create table Customers(
CustId int auto_increment primary key,
FirstName nvarchar(50),
LastName nvarchar(50)
);

insert into Customers(FirstName, LastName)


values ('Dave', 'Brenner'),
('Matt', 'Walton'),
('Steve', 'Hagen'),
('Pat', 'Walton');
Creating the database AutoLot
create table Orders(
OrderId int primary key auto_increment,
CustId int,
CarId int,
foreign key (CustId) references Customer(CustId),
foreign key (CarId) references Inventory(CarId)
);
insert into Orders(CustId, CarId)
values(1, 5), (2, 1), (3, 4), (4, 7);
Simple ADO.NET to MySQL Example
namespace ADOTest
{
class MainClass
{
public static void Main(string[] args)
{
using (MySql.Data.MySqlClient.MySqlConnection con = new MySql.Data.MySqlClient.MySqlConnection(
"Server=localhost;PORT=8889;DATABASE=AutoLot;USER=root;PASSWORD=root")){
//Open connction
con.Open();
//Make a command
DbCommand cmd = con.CreateCommand();
cmd.CommandText = "Select * from Inventory";
using(DbDataReader dataReader = cmd.ExecuteReader()){
while(dataReader.Read()){
Console.WriteLine($"Car {dataReader["CarId"]} is a {dataReader["Make"]}.");
}
}
}
}
}
}

Note:
For this example to run, you need to add the MySql.Data Package.
Summary
References
Troelsen, A. & Japikse, P., 2015. C# 6 and the
.NET 4.6 Framework. 7th ed. Apress.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy