Database Access
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
Reference type
In Form2 class
public Form2(string CustomerName)
Passing data between 2 forms
Specify as a data field and Property
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
lblSubjectName.Text = dStudents.Tables["Subject"].Rows[0]["SubjectName"].ToString();
Display of students taking a subject
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
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, " +
if (sortColumns.Trim() == "")
sqlCommand += "ORDER BY EmployeeID";
else
sqlCommand += "ORDER BY " +
sortColumns;
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();
dConn.Open();
int x = updateCmd.ExecuteNonQuery();
55
Updating DataSet
Reflects current state of data
When an Update occurs
When Delete occurs
Cannot reread database everytime
Remember DataSet in memory
// Clear fields
txtFirstName.Clear();
txtLastName.Clear();
txtPhone.Clear();
// Update the combobox
cmbStudents.DataSource = ds.Tables[0];
cmbStudents.DisplayMember = "StudentID";
row["LastName"] = txtLastName.Text;
row["PhoneNumber"] = txtPhone.Text;
row.EndEdit();
}
}
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");
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();
dbDataAdapter.SelectCommand = dbCmd;
dbDataAdapter.Fill(dStudents, "Students");
grvStudentMarks.DataSource = dStudents.Tables["Students"];
Student Application - databases
Student Application
lstStudentSubject.Items.RemoveAt(lstStudentSubject.SelectedIndex);
}
Using
single select
Code for Add Wizard – Second
section
3. Updating the StudentMarks table in btnRegister_Click(…..)
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();
}
}