Lecture 10: Database Lisa (Ling) Liu: C# Programming in Depth
Lecture 10: Database Lisa (Ling) Liu: C# Programming in Depth
C# Programming in Depth
Prof. Dr. Bertrand Meyer
March 2007 – May 2007
Employee
EmployeeID Title ManagerID VacationHours
1 Production 16 21
Technician
2 Marketing 6 42
Assistant
3 Engineering 12 2
Manager
4 Senior Tool 3 48
Designer
Employee
EmployeeID Title ManagerID VacationHours
1 Production 16 21
Technician
2 Marketing 6 42
Assistant
3 Engineering 12 2
Manager
4 Senior Tool 3 48
Designer
Primary key
1 PT 16 21
2 MA 6 42
3 EM 12 2
4 STD 3 48
EmployeeID establishs a
relationship between the
EmployeePayHistory tables.
EmployeeID RateChangeDate Rate
1 31.07.1996 12.4500
2 26.02.1997 13.4615
3 12.12.1997 43.2692
4 05.01.1998 8.6200
4 01.07.2000 23.7200
4 15.01.2002 29.8462
Employee We say that there is a
EmployeeID Title ManagerID VacationHours “foreign key constraints”
between the tables.
1 PT 16 21
1 31.07.1996 12.4500
2 26.02.1997 13.4615
3 12.12.1997 43.2692
Foreign key
Simple SQL Queries
SELECT
1 PT 16 21
2 MA 6 42
3 EM 12 2
4 STD 3 48
1 16
2 6
4 3
How to interact with data stores?
ADO.NET
a set of namespaces defined on .NET platform that understand how to
interact with data stores.
¾ native support for SQL Server and Oracle
¾ support for other databases via older OleDB
technology
¾ requires a knowledge of SQL
Delete Command
DataReader Object
using System.Data;
using System.Data.SqlClient;
...
MessageBox.Show( cn.State.ToString() );
while (myDataReader.Read())
{
Console.WriteLine("EmployeeID: {0}, Title: {1}, ManagerID: {2}, VacationHours: {3}",
myDataReader["EmployeeID"].ToString().Trim(),
myDataReader["Title"].ToString().Trim(),
myDataReader["ManagerID"].ToString().Trim(),
myDataReader["VacationHours"].ToString().Trim());
}
cn.Close();
try {
cn.Open();
.
.
.
}
catch(Exception ex) {
System.Diagnostics.EventLog.WriteEntry("MyApp", ex.Message);
System.Diagnostics.EventLog.WriteEntry("MyApp", ex.StackTrace);
throw ex;
}
finally {
if ((cn != null) && (cn.State != ConnectionState.Closed))
cn.Close();
}
try
{
cmd.ExecuteNonQuery();
}
catch
{
Console.WriteLine("Sorry! That employ cannot be deleted.");
}
SqlDataAdapter
• SqlCommand
− “SELECT * FROM Table1” SQL Server
− Sql Connection
• Fill (myDataSet, “myTable”)
Client Application
DataSet
SQL
Database
Forms
DataSet
DataTablesCollection
DataRelationCollection
PropertyCollection
PrintDataSet(myDS);
myAdapter.InsertCommand = insertCmd;
carName = myDS.Tables[“Inventory"].Rows[0][“PetName”]
carName = myDs.Inventory[0].PetName;