Вы находитесь на странице: 1из 88

Database Access

 Access
 SQL Server
 SQL statements
Outline
 Relational Database Management Concepts
 Introduction to Database Access in C#
 ADO.NET
 Data Providers
 Accessing data in tables
Moodle Site
 SQL101 Structured Query Language

 http://learn.nmmu.ac.za/login/index.php
◦ Login in
◦ Go to School of ICT
◦ Go to SQL101 course

 Enrolment key: SQLpower


Database Access
 Example DBMS include SQL server, Oracle,
and Access
◦ Many DBMSs store data in tabular format
 Data in tables are related through common data field
keys
 Typically use a query language to program
database access
◦ Structured query language (SQL)
 ActiveX Data Objects (ADO.NET)—.NET data
access technology for accessing data in
databases
Microsoft Visual C# .NET: From
Problem Analysis to Program
Design
5
ADO.NET
 Includes number of classes that can be used to
retrieve, manipulate, and update data in
databases
 Can work with databases in a disconnect
manner
◦ Database table(s) can be retrieved to a temporary file
 To retrieve data first you must connect to the
database
 ADO.NET uses a feature called data providers
to connect, execute commands, and retrieve
results from a database
Microsoft Visual C# .NET: From
Problem Analysis to Program
Design
6
Data Providers
 Microsoft SQL Server
◦ Applications using SQL Server 7.0 or later
 Oracle
◦ Applications using Oracle data sources
 Object Linking and Embedding Database
(OLE DB)
◦ Applications that use Microsoft Access
databases
 Open Database Connectivity (ODBC)
◦ Applications supported by earlier versions of
Visual Studio
Microsoft Visual C# .NET: From
Problem Analysis to Program
Design
7
Data Providers (continued)
 Classes are encapsulated into a different
namespace by provider
 Four core classes make up each data provider
namespace:
◦ Connection—Establishes a connection to a data
source
◦ Command—Executes a command against a data
source
◦ DataReader—Performs a forward-only (sequential)
access of the data in the data source
◦ DataAdapter—Populates a dataset and updates the
database
Microsoft Visual C# .NET: From
Problem Analysis to Program
Design
8
Connecting to the Database
(Microsoft Access DBMS)
 Add using directive
using System.Data.OleDb;
 Instantiate an object of connection class
◦ Send connection string that includes the actual
database provider and the data source (name of the
database)
string sConnection;
sConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=member.mdb";
OleDbConnection dbConn;
dbConn = new OleDbConnection(sConnection); Enclose
dbConn.Open(); in try…
catch
Microsoft Visual C# .NET: From block
Problem Analysis to Program
Design
9
Access 2007
string sConnection;
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=member.accdb";
OleDbConnection dbConn;
dbConn = new OleDbConnection(sConnection);
dbConn.Open();

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
10
Data Providers & paths
 Provider=Microsoft.ACE.OLEDB.12.0;Data
Source="C:\Documents and
Settings\mchct\My Documents\c#.accdb"

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
11
Retrieving Data from the Database
 One way to retrieve records programmatically—
issue an SQL query
 Object of OleDbCommand class used to hold SQL
string sql;
sql = "Select * From memberTable Order By LastName Asc, "
+ "FirstName Asc;"; // Note the two semicolons
OleDbCommand dbCmd = new OleDbCommand();
dbCmd.CommandText = sql; // set command SQL string
dbCmd.Connection = dbConn; // dbConn is connection object

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
12
SQL Queries
 Select * From memberTable Order By
LastName Asc, FirstName Asc;
◦ Asterisk (*) selects all fields (columns) in database
 Can replace * by field name(s)

◦ Asc—(ascending) returns in ascending order by


LastName; duplicate last names ordered by first
name
◦ Retrieves all rows (records)
 Where clause can be added
Select PhoneNumber From memberTable Where FirstName = 'Gary'
AND LastName = 'Jones';

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
13
Data Providers
 Provider=Microsoft.ACE.OLEDB.12.0;Data
Source="C:\Documents and
Settings\mchct\My Documents\c#.accdb“
◦ For Access v 7.0
 Provider=Microsoft.Jet.OLEDB.4.0;Data
Source="C:\Documents and
Settings\mchct\My Documents\c#.mdb“

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
14
Retrieving Data from the Database
 Select StudentID, FirstName, LastName,
PhoneNumber From memberTable;

Microsoft Visual C# .NET: From


Problem Analysis to Program Design
15
Processing Data
 Can retrieve one record at a time in memory
◦ Process that record before retrieving another
 OR can store the entire result of the query in
temporary data structure similar to an array
◦ Disconnect from the database
 ADO.NET includes data reader classes (by
provider)
◦ Used to read rows of data from a database

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
16
Retrieving Data Using a Data Reader
 OleDbDataReader class
◦ READ-ONLY access
◦ Forward retrieval (sequential access)
◦ Results returned as query executes
 Sequentially loop through the query results
 Only one row is stored in memory at a time
 Useful to accessing data from large database tables
 Declare an object of the OleDbDataReader
class
 Call ExecuteReader( ) method
Microsoft Visual C# .NET: From
Problem Analysis to Program
Design
17
Retrieving Data Using a Data Reader
(continued)

 To position the OleDbDataReader object onto


the row of the first retrieved query result, use
Read( ) method of the OleDbDataReader class
◦ Read( ) also used to advance to the next record
◦ Think about what is retrieved as one-dimensional
table consisting of the fields from that one row
 Fields can be referenced using actual ordinal index
 Fields can also be referenced using the table's field names
as indexers to the data reader object

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
18
Retrieving Data Using a Data
Reader (continued)
 First call to dbReader.Read( ) retrieves first row
◦ dbReader[0] refers to 1234
◦ dbReader[1] refers to “Rebecca”
◦ dbReader["FirstName"] also refers to "Rebecca"

Field name must


be enclosed in
double quotes
when used as
indexers

Microsoft Visual C# .NET: From


Problem Analysis to Proram Design
19
Retrieving Data Using a Data Reader
(continued)
Member aMember;
OleDbDataReader dbReader;
dbReader = dbCmd.ExecuteReader( ); // dbCmd—
OleDbCommand object
while (dbReader.Read( ))
{ // retrieve records 1-by-1...
aMember = new Member(dbReader["FirstName"].ToString( ),
dbReader["LastName"].ToString( ));
this.listBox1.Items.Add(aMember);
}
dbReader.Close(); // Close the Reader object
dbConn.Close(); // Close the Connection object
Microsoft Visual C# .NET: From
Problem Analysis to Program
Design
20
Retrieving Data Using a Data Reader
(continued)

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
21
Retrieving Data Using a Data Reader
(continued)

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
22
Retrieving Data Using a Data Reader— DBExample
Application

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
23
Retrieving Data – Single View
 Load records into arrays (parallel arrays OR
you could use array of Members)
 Read all records from Members table

◦ Load into array/s


 Use the array/s to traverse through records,
using Next button

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
24
Retrieving data – Single View
 Records loaded into
arrays
 When Next button

pressed, the next


element in array is
processed

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
25
ArrayList class
 Limitations of traditional array:
◦ Cannot change the size or length of an array
after it is created
 ArrayList class facilitates creating listlike
structure, BUT it can dynamically increase
or decrease in length
◦ Similar to vector class found in other
languages
 Includes large number of predefined
methods
Microsoft Visual C# .NET: From
Problem Analysis to Program Design
26
ArrayList Class (continued)

Microsoft Visual C# .NET: From


Problem Analysis to Program Design
27
String Class
 Store a collection of Unicode characters
 Immutable series of characters

 Reference type

◦ Normally equality operators, == and !=,


compare the object’s references—but
operators function differently with string than
with other reference objects
 Equality operators are defined to compare the
contents or values
 Includes large number of predefined
methods
Microsoft Visual C# .NET: From
Problem Analysis to Program Design
28
String Class (continued)

Microsoft Visual C# .NET: From


Problem Analysis to Program Design
29
String Class (continued)

Microsoft Visual C# .NET: From


Problem Analysis to Program Design
30
String Class (continued)

Microsoft Visual C# .NET: From


Problem Analysis to Program Design
31
Passing data between 2 forms
 Specify as a parameter on constructor

In class that call Form2


belleAireForm = new Form2(CustName.Text);

In Form2 class
public Form2(string CustomerName)
Passing data between 2 forms
 Specify as a data field and Property

In class that call Form3


 LincolnForm = new Form3();
 LincolnForm.myCustomer = CustName.Text;

In Form3 class
string CustomerName;
public string myCustomer
{get { return CustomerName;}
set { CustomerName = value;}
}
Filling the Dataset using the Data
Adapter
 After instantiating objects of data adapter,
dataset, and command builder classes
 Using data adapter Fill( ) method to specify
name of table to use as the data source
memberDataAdap.Fill(memberDS, "memberTable");
 To show contents of table, presentation user
interface layer is needed
◦ Grid control works well

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
34
Creating a DataGrid to Hold the
Dataset
 Place DataGridView control object on Windows
Form
◦ DataGridView object can be selected from ToolBox
◦ Able to navigate around in data grid
◦ Can make changes by editing current records
◦ Can insert and delete new records
 To tie DataGridView object to dataset, DataSource
property is used
this.dataGrid1.DataSource = memberDS.["memberTable“]; OR
This.dataGrid1.DataSource = memberDS.Tables[0];
Microsoft Visual C# .NET: From
Problem Analysis to Program
Design
35
Multiple tables in Database
Querying multiple tables
 Simple query – SELECT with only single tables
 Query combining more than 1 table in SELECT
 One to many relationships
Load of Subject combobox
dbConn = new OleDbConnection(sConnection);

string sql = "Select * From SubjectTable";


dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;

dbDataAdapter = new OleDbDataAdapter();


dbDataAdapter.SelectCommand = dbCmd;
ds = new DataSet();
dbDataAdapter.Fill(ds, "Subjects");
cmbSubjects.DataSource = ds.Tables["Subjects"];
cmbSubjects.DisplayMember = "SubjectCode";
Display of subject name
DataSet dStudents = new DataSet();

string sqlSubject = "Select * from SubjectTable WHERE SubjectCode = @subject";


dbCmd = new OleDbCommand(sqlSubject, dbConn);
dbCmd.Parameters.AddWithValue("@subject", cmbSubjects.Text);
DataSet dSubject = new DataSet();
dbDataAdapter.SelectCommand = dbCmd;
dbDataAdapter.Fill(dStudents, "Subject");
if(dStudents.Tables["Subject"].Rows.Count >0

lblSubjectName.Text = dStudents.Tables["Subject"].Rows[0]["SubjectName"].ToString();
Display of students taking a subject

string sqlStudents = "Select * From StudentMarks WHERE SubjectCode = @subject";


dbCmd = new OleDbCommand(sqlStudents, dbConn);
dbCmd.Parameters.AddWithValue("@subject", cmbSubjects.Text);

dbDataAdapter.SelectCommand = dbCmd;
dbDataAdapter.Fill(dStudents, "Students");
grvStudentMarks.DataSource = dStudents.Tables["Students"];
SELECT statement accessing 2 tables
SELECT t1.col2, t1.col3, t2.col1, t1.col4
FROM t1, t2
WHERE
t1.col1 = t2.col1
Display students and their names

string sqlStudents = "Select StudentMarks.StudentID,


memberTable.FirstName, memberTable.LastName, StudentMarks.Mark
From StudentMarks, memberTable WHERE StudentMarks.StudentID =
memberTable.StudentID AND SubjectCode = @subject";

dbCmd = new OleDbCommand(sqlStudents, dbConn);


dbCmd.Parameters.AddWithValue("@subject", cmbSubjects.Text);

dbDataAdapter.SelectCommand = dbCmd;
dbDataAdapter.Fill(dStudents, "Students");
grvStudentMarks.DataSource = dStudents.Tables["Students"];
Query 3 tables
SELECT with 3 tables
DataSet dStudents = new DataSet();
string sConnection =
"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=member.mdb";
dbConn = new OleDbConnection(sConnection);
string sqlStudents = "Select StudentMarks.StudentID, memberTable.FirstName, " +

"memberTable.LastName, StudentMarks.SubjectCode, SubjectTable.SubjectName,


StudentMarks.Mark " +

"FROM StudentMarks, memberTable, SubjectTable WHERE StudentMarks.StudentID =


memberTable.StudentID AND StudentMarks.SubjectCode = SubjectTable.SubjectCode";

dStudents = new DataSet();


dbCmd = new OleDbCommand(sqlStudents, dbConn);
dbDataAdapter = new OleDbDataAdapter(dbCmd);
dbDataAdapter.Fill(dStudents, "Students");
grvAllStudents.DataSource = dStudents.Tables["Students"];
Updating SELECT statement
sqlCommand = “SELECT * FROM EmpTable”;

if (sortColumns.Trim() == "")
    sqlCommand += "ORDER BY EmployeeID";
  else
    sqlCommand += "ORDER BY " +
sortColumns;

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
46
Updating Database Data
 Data Reader enables read-only access to
database
 Several ways to change or update database
◦ Can write Insert, Delete, and Update SQL statements
and then execute those queries by calling
OleDbCommand.ExecuteNonQuery( ) method
◦ Can instantiate objects of dataset and data adapter
classes
 Use data adapter object to populate dataset object
 Adapter class has Fill( ) and Update( ) methods

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
47
Updating Database Data (continued)
 Not required to keep a continuous live
connection
◦ Can create temporary copy in memory of the
records retrieved using a dataset
 Interaction between dataset and actual
database is controlled through data adapter
 Each of the different data providers has its
own dataset and data adapter objects
◦ System.Data.OleDb—Access database
Microsoft Visual C# .NET: From
Problem Analysis to Program
Design
48
Using Datasets to Process Database
Records
 Instantiate a connection object using
connection string
◦ Not necessary to call Open( ) method
 Select records (and fields) from database by
executing SQL Select
 Instantiate object of Dataset class (for a table)
DataSet memberDS = new DataSet();
 Instantiate an object of DataAdapter class
OleDbDataAdapter memberDataAdap = new
OleDbDataAdapter( );

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
49
Inserting Records
 Use INSERT command
INSERT INTO table name (column names)
VALUES (…,….,…)
Eg
INSERT INTO MemberTable (StudentID,
FirstName, LastName, Phone) VALUES (
‘11111’, ‘Karen’, ‘Church’, ‘0415831757’)

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
50
    objConnection = new OleDbConnection(strConnection);
    objConnection.ConnectionString = strConnection;

    objConnection.Open();
    
    // set the SQL string
    strSQL = "INSERT INTO Employee (FirstName , LastName ) " +
    "VALUES ( 'Beth' , 'Hart' )";

    // Create the Command and set its properties
    objCmd = new OleDbCommand(strSQL, objConnection);
    
    // execute the command
    objCmd.ExecuteNonQuery();

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
51
Parameters in INSERT command

sql = "INSERT INTO memberTable (StudentID, FirstName,


LastName,PhoneNumber)VALUES(?, ?, ?, ?)";

OleDbCommand insertCmd = new OleDbCommand(sql, dbConn);


insertCmd.Parameters.Add("StudentID", OleDbType.Char).Value = txtStudID.Text;
insertCmd.Parameters.Add("FirstName", OleDbType.Char).Value = txtFirstname.Text;
insertCmd.Parameters.Add("LastName", OleDbType.Char).Value = txtLastName.Text;
insertCmd.Parameters.Add("PhoneNumber", OleDbType.Char).Value =
txtphone.Text;

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
52
UPDATE command
string sql = "UPDATE memberTable SET FirstName = @First, LastName = @Last,
PhoneNumber = @Phone WHERE (StudentID = @ID)"
updateCmd = new OleDbCommand(sql, dConn);
updateCmd.Parameters.AddWithValue("@First", txtFirstName.Text.ToString());
updateCmd.Parameters.AddWithValue("@Last", txtLastName.Text.ToString());
updateCmd.Parameters.AddWithValue("@Phone", txtPhone.Text.ToString());
updateCmd.Parameters.AddWithValue("@ID", cmbStudents.Text.ToString());

dConn.Open();
int x = updateCmd.ExecuteNonQuery();

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
53
DELETE command

string sql = "DELETE FROM memberTable WHERE (StudentID = @ID)";


deleteCmd = new OleDbCommand(sql, dConn);
string deletestudent = cmbStudents.Text;
// Confirm Delete
deleteCmd.Parameters.AddWithValue("@ID",
cmbStudents.Text.ToString());
if (MessageBox.Show("Do you really want to delete this student?",
"Delete Confirmation",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
DialogResult.Yes) {
dConn.Open();
int x = deleteCmd.ExecuteNonQuery();

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
54
INSERT – AutoNumber key

sql = "INSERT INTO Table1 (CustomerNumber,CustomerName,Area) VALUES


(?,?,?)";
cmd = new OleDbCommand();
cmd.CommandText = sql;
cmd.Connection = connection;
cmd.Parameters.Add("CustomerNumber", OleDbType.Numeric).Value =
int.Parse(txtCustNumber.Text);
cmd.Parameters.Add("CustomerName", OleDbType.Char).Value =
txtCustName.Text;
cmd.Parameters.Add("Area", OleDbType.Char).Value = txtCustArea.Text;
int x = cmd.ExecuteNonQuery();

55
Updating DataSet
 Reflects current state of data
 When an Update occurs
 When Delete occurs
 Cannot reread database everytime
 Remember DataSet in memory

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
56
Delete action
foreach (DataRow row in ds.Tables[0].Rows)
if (row["StudentID"] == deletestudent)
{
row.Delete();
}

// Clear fields
txtFirstName.Clear();
txtLastName.Clear();
txtPhone.Clear();
// Update the combobox
cmbStudents.DataSource = ds.Tables[0];
cmbStudents.DisplayMember = "StudentID";

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
57
Update action
foreach (DataRow row in ds.Tables[0].Rows)
{
if (row["StudentID"] == studentId)
{
row.StartEdit();
row["FirstName"] = txtFirstName.Text;

row["LastName"] = txtLastName.Text;

row["PhoneNumber"] = txtPhone.Text;
row.EndEdit();
}
}

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
58
Add action
DataSet ds;
public AddForm(DataSet da)
{
InitializeComponent();
ds = da;

int x = insertCmd.ExecuteNonQuery();
ds.Tables[0].Rows.Add(new Object[] {txtStudID.Text, txtFirstname.Text,
txtLastname.Text, txtphone.Text});
txtStudID.Clear();
txtFirstname.Clear();
txtLastname.Clear();
txtphone.Clear();
Microsoft Visual C# .NET: From
Problem Analysis to Program
Design
59
Command Builder Class
 Class that automatically generates SQL for
updates
◦ Must set the SelectCommand property of the
OleDbDataAdapter class
See slide 53 –
private OleDbCommandBuilder cBuilder;
dbCmd set
: the SQL Select
cBuilder = new
OleDbCommandBuilder(memberDataAdap);
memberDataAdap.SelectCommand = dbCmd;
 CommandBuilder object only used for
datasets that map to a single database
table
Microsoft Visual C# .NET: From
Problem Analysis to Program
Design
60
Updating the Database
 Load the database into a DataGrid object and
make changes
 Flush the changes back up to live database using
the Update( ) method of DataAdapter class

memberDataAdap.Update(memberDS,
"memberTable");

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
61
Updating the Database —
DataSetExample Application

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
62
Updating the Database —
DataSetExample Application

Microsoft Visual C# .NET: From


Problem Analysis to Program
Design
63
Passing connection, command
Calling Class
frmMarksQuery subjectform = new frmMarksQuery(dbConn, dbCmd,
dbDataAdapter);
subjectform.ShowDialog();

Called Class
public frmMarksQuery(OleDbConnection dbConn, OleDbCommand
dbCmd, OleDbDataAdapter dbDataAdapter )
{
this.dbConn = dbConn;
this.dbCmd = dbCmd;
this.dbDataAdapter = dbDataAdapter;
InitializeComponent();
}
Using passed connection, command

dbCmd.CommandText = sql;

dbDataAdapter.SelectCommand = dbCmd;
ds = new DataSet();
dbDataAdapter.Fill(ds, "Subjects");
cmbSubjects.DataSource = ds.Tables["Subjects"];
cmbSubjects.DisplayMember = "SubjectCode";
Passing parameter example
Using passed connection, command
DataSet dStudents = new DataSet();
string sqlSubject = "Select * from SubjectTable WHERE SubjectCode =
@subject";
dbCmd = new OleDbCommand(sqlSubject, dbConn);
dbCmd.Parameters.AddWithValue("@subject", cmbSubjects.Text);
dbDataAdapter.SelectCommand = dbCmd;
dbDataAdapter.Fill(dStudents, "Subject");
if(dStudents.Tables["Subject"].Rows.Count >0)
lblSubjectName.Text = dStudents.Tables["Subject"].Rows[0]
["SubjectName"].ToString();

string sqlStudents = "Select StudentMarks.StudentID, memberTable.FirstName,


memberTable.LastName, StudentMarks.Mark From StudentMarks, memberTable
WHERE StudentMarks.StudentID = memberTable.StudentID AND SubjectCode =
@subject";
dbCmd = new OleDbCommand(sqlStudents, dbConn);
dbCmd.Parameters.AddWithValue("@subject", cmbSubjects.Text);

dbDataAdapter.SelectCommand = dbCmd;
dbDataAdapter.Fill(dStudents, "Students");
grvStudentMarks.DataSource = dStudents.Tables["Students"];
Student Application - databases
Student Application

Student menu option – only has Add Wizard


Subject menu option – only has View Subject (class list)
Student – Add Wizard
Subject –Subject View
Code for Add Wizard – First
section
Add student details to memberTable
private void btnAddStudent_Click(object sender, EventArgs e) This adds the
{ student to the
memberTable
if(dbConn.State.ToString() == "Closed")
dbConn.Open();
string sql = "INSERT INTO memberTable (StudentID, FirstName, LastName,
PhoneNumber) VALUES(?, ?, ?, ?)";
dbCmd = new OleDbCommand(sql, dbConn);
dbCmd.Parameters.Add("StudentID", OleDbType.Char).Value = txtStudentID.Text;
dbCmd.Parameters.Add("FirstName", OleDbType.Char).Value = txtFirst.Text;
dbCmd.Parameters.Add("LastName", OleDbType.Char).Value = txtLast.Text;
dbCmd.Parameters.Add("PhoneNumber", OleDbType.Char).Value = txtPhone.Text;
dbCmd.ExecuteNonQuery();
pnlRegister.Visible = true;
dbCmd.CommandText = "Select * FROM SubjectTable"; This loads
dbDataAdapter.SelectCommand = dbCmd;
Subjects listbox
dbDataAdapter.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
and makes the
{ 2nd panel visible
lstAllSubject.Items.Add(row["SubjectCode"]);
}
}
Code for Add Wizard – Second
section
1. Adding subjects to the studentRegister listbox

private void btnAddSubject_Click(object sender, EventArgs e)


{ Catering for
foreach (int i in lstAllSubject.SelectedIndices) multiple
{ select
lstStudentSubject.Items.Add(lstAllSubject.Items[i]);
}
}

2. Removing subjects from the student subject listbox

private void btnRemoveSubject_Click(object sender, EventArgs e)


{

lstStudentSubject.Items.RemoveAt(lstStudentSubject.SelectedIndex);
}
Using
single select
Code for Add Wizard – Second
section
3. Updating the StudentMarks table in btnRegister_Click(…..)

foreach (string subject in lstAllSubject.Items)


{
string sql = "INSERT INTO StudentMarks(StudentID, SubjectCode,Mark)" +
" VALUES(?, ?,0)";
dbCmd = new OleDbCommand(sql, dbConn);
dbCmd.Parameters.Add("StudentID", OleDbType.Char).Value = txtStudentID.Text;
dbCmd.Parameters.Add ("SubjectCode", OleDbType.Char).Value = subject;
dbCmd.ExecuteNonQuery();
}
Code for Add Wizard – Second
section
4. Confirmation & clearing fields in btnRegister_Click(…..)

if (MessageBox.Show("Student is registered. Do you want to add another


student?", "Confirmation", MessageBoxButtons.YesNo) ==
DialogResult.Yes)
{
txtStudentID.Clear();
txtFirst.Clear();
txtLast.Clear();
txtPhone.Clear();
lstAllSubject.Items.Clear();
lstStudentSubject.Items.Clear();
pnlRegister.Visible = false;
}
else
Application.ExitThread();
}
Exceptions
 System Exceptions
 Application Exceptions
 User-defined Exceptions

 try/catch/finally
Exceptions
 System.OutOfMemoryException
 System.NumberFormatException
 System.NullReferenceException
 System.InvalidCastException
 System.ArrayTypeMismatchException
 System.IndexOutOfRangeException        
 System.ArithmeticException
 System.DivideByZeroException
 System.OverFlowException 
Exceptions
 SecurityException
 ArgumentException
 ArgumentNullException
 PathTooLongException
 DirectoryNotFoundException
 UnauthorizedAccessException
 FileNotFoundException
 NotSupportedException
Exception information
string str;
str = "Source:"+ ex.Source;        
str += "\n"+ "Number:"+ ex.Number.ToStrin
g();
str += "\n"+ "Message:"+ ex.Message;
str += "\n"+ "Class:"+ ex.Class.ToString ();
str += "\n"+ "Procedure:"+ ex.Procedure.ToS
tring();
str += "\n"+ "Line Number:"+ex.LineNumber.
ToString();
str += "\n"+ "Server:"+ ex.Server.ToString();
Exceptions
try
{…}
catch(OleDbException ex)
{…}
catch(Exception ex)
{…}
finally
{…}
Database Exceptions
 Check the connection
 Check the statements
 Check if IO occurred successfully
 OleDbException/DbException
 SQLException
 Exception
 Single/Multiple Exceptions
Exception Example
private void Commitbutton_Click(object sender, EventArgs e)
{ try
{
dataAdapter.Update(table);
BindSource.EndEdit();
table.EndInit();
table.AcceptChanges();
}
catch (SqlException sqlex)
{
Console.WriteLine(sqlex);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
Exception example
OleDbConnection aConnection = new
OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\db1.mdb");
//create the command object and store the sql query
OleDbCommand aCommand = new OleDbCommand("select * from emp_test",
aConnection);
try
{
aConnection.Open();
//create the datareader object to connect to table
OleDbDataReader aReader = aCommand.ExecuteReader();
Console.WriteLine("This is the returned data from emp_test table");
Exception Example (cont)
//Iterate through the database
while(aReader.Read())
{
Console.WriteLine(aReader.GetInt32(0).ToString());
}
//close the reader
aReader.Close();
//close the connection Its important.
aConnection.Close();
}
//Some usual exception handling
catch(OleDbException e)
{
Console.WriteLine("Error: {0}", e.Errors[0].Message);
}
}
2nd Example
string connString = "server=(local)\\SQLEXPRESS;database=My
Database;Integrated Security=SSPI";

         SqlConnection conn = new SqlConnection(connString);

         SqlCommand cmd = conn.CreateCommand();
      
         cmd.CommandType = CommandType.StoredProcedure;
 
         cmd.CommandText = "something wrong here";

         try {
            conn.Open();
 
            SqlDataReader dr = cmd.ExecuteReader();

            string str = dr.GetValue(20).ToString();

            dr.Close();
         }
2nd Example
         catch (System.InvalidOperationException ex)
         {
            string str;
            str = "Source:" + ex.Source;
            str += "\n" + "Message:"+ ex.Message;
            str += "\n" + "\n";
            str += "\n" + "Stack Trace :" + ex.StackTrac
e;
            MessageBox.Show (str, "Specific Exception")
;
         }
         
2nd Example
catch (System.Data.SqlClient.SqlException ex)
         {
            string str;
            str = "Source:" + ex.Source;
            str += "\n" + "Message:" + ex.Message;
           MessageBox.Show (str, "Database Exception"
);
}
catch (System.Exception ex)
         {
            string str;
            str = "Source:" + ex.Source;
             str += "\n"+ "Message:" + ex.Message;
            Console.WriteLine (str, "Generic Exception");
         }
2nd Example
finally
{
if ( conn.State == ConnectionState.Open)
   {
    MessageBox.Show ("Finally block closing 
the connection",  "Finally");
    conn.Close();
    }
}

Вам также может понравиться