Chapter 5
Chapter 5
4
Connection: directs communication between your program and the
data source. It includes properties and methods that let you indicate the
location or connection parameters for the data
source(SqlConnection,OleDBConnection)
Command: takes the SQL statement you provide, and prepares it for
transport through the Connection object(SqlCommand,
OleDBCommand)
DataReader: provides a simple and efficient way to retrieve results
from a data query. but your code can use it directly to process the
results of a SELECT statement or other data retrieval action
(SqlDataReader, OleDBDataReader)
DataSet: provides a generic disconnected view of data, whether it is
data from a provider, or data that you build through code.
DataAdapter: makes communication between a data set and the rest
of a provider possible. One of its primary jobs is to modify data
manipulation statements (the SELECT, INSERT, UPDATE, and DELETE
statements) generated by a data set into a format that can be used by the
related data source.(SqlDataAdapter,OleDBDataAdapter)
The Connection Object is what you need if you want to
connect to a database.
There are a number of different connection objects, and the
one you use depends largely on the type of database you're
connecting to.
E.g. To connect an Access database, we need the OLE DB connection
object. OLE stands for Object Linking and Embedding.
You can use it, for example, to connect to text files, SQL
Server, email, etc.
There are a number of different OLE DB objects (called data
providers), "Jet“, SQL Server and Oracle.
6
So place a button on your form. Change the Name property to
btnLoad. Double click your button to open up the code window.
Add the following line: System.Data.OleDb.OleDbConnection con;
Setting a Connection String
There are Properties and Methods associated with the Connection
Object, of course. We want to start with the ConnectionString
property. This can take MANY parameters . Fortunately, we only need a
few of these.
We need to pass two things to our new Connection Object: the
technology we want to use to do the connecting to our database; and
where the database is. (If your database was password and user name
protected, you would add these two parameters as well. Ours isn't, so
we only need the two.)
The technology is called the Provider; and you use "Data Source" to
specify where your database is. This should be entered on the same line.
7
Open method of the Connection Object is used to open connection.
Close method of the Connection Object is used to close connection.
Add the following code on btnLoad.
OleDbConnection con=new OleDbConnection();
con.ConnectionString = "provider= Microsoft.ACE.OLEDB.12.0; Data
Source=C:\\CSE_DEPT.accdb";
con.Open();
MessageBox.Show("A Connection to the Database is now open");
con.Close();
MessageBox.Show ("The Connection to the Database is now Closed");
Run and click on the button
You should see the two message boxes displayed
con.ConnectionString ="PROVIDER=Microsoft.Jet.OLEDB.4.0;Data
Source =C:\\AddressBook.mdb"; -MS Access 2003
8
For SQL Server we have written the following connection string:
string connectionString = "server=localhost; database=dimotest; uid=user;
pwd=nicecoding;“;
Where localhost is computer(server) name, dimotest is database name, user is
user name, pwd is password
Example:
using System.Data.SqlClient;
SqlConnection myconn;
myconn = new SqlConnection("Database=CSE_DEPT;server=worku-
pc;Integrated Security=True");
myconn.Open();
MessageBox.Show("Opened");
myconn.Close();
MessageBox.Show("Closed");
When Integrated Security or Trusted_Connection is false we have to enter user
id and password. True and SSPI (Security Support Provider Interface) are the
same.
ADO.NET uses something called a DataSet to hold all of your
information from the database (you can also use a DataTable,
if all you want to do is read information, and not have people
write to your database.).
But the DataSet (and Data Table) will hold a copy of the
information from the database.
The Connection Object and the DataSet can't see each other.
They need a go-between so that they can communicate. This
go-between is called a Data Adapter.
The Data Adapter contacts your Connection Object, and then
executes a query that you set up.
The results of that query are then stored in the DataSet.
10
The Data Adapter and DataSet are objects. They are set up like
this:
DataSet ds=new DataSet();
OleDbDataAdapter da;
string sql;
sql = "SELECT * FROM student";
da = new OleDbDataAdapter(sql, con);
The Data Adapter is a property of the OLEDB object, hence the
full stop between the two. We're passing this object to the
variable called da. This variable will then hold a reference to the
Data Adapter.
The fifth line from the above code fragment needs two
11
parameters sql string and connection object.
The Data Adapter can Fill a DataSet with records from a Table.You
only need a single line of code to do this:
da.Fill(ds, “StudInfo");
ds is the name of the dataset created earlier and the second argument
“StudInfo” is an identifying name-This identifying name can be
anything you like- but it is better to chose descriptive name.
------sql equivalent-----------------------------------
DataSet ds=new DataSet();
SqlDataAdapter da;
string sql;
sql = "SELECT * FROM student";
da = new SqlDataAdapter(sql, myconn);
da.Fill(ds, "StudInfo");
12
Now lets display the records on a Form, so that people can see them.
Add two textboxes to your form
Change the Name properties of your textboxes to txtID and txtname
Go back to your code window add the following two lines:
txtId.Text =
Convert.ToString(ds.Tables["StudInfo"].Rows[0].ItemArray[0]);
txtName.Text =
Convert.ToString(ds.Tables["StudInfo"].Rows[0].ItemArray[1]);
You can add them after the line that closes the connection to the database.
Once the DataSet has been filled, a connection to a database can be
closed.
ds is the name of the dataset. Then Tables property is called with the name of the
table we gave during ds is filled with data.
The image shows which are the Rows and which are the Items in
the Access database Table.
So the Items go down and the Rows go across.
But we want to navigate increment the row number
14
It is possible to navigate through the records of a database by
incrementing or decrementing the Row number of the DataSet.
To see how to do that create a new project add two textboxes
with txtID and txtname names and four buttons.
Button Name Button Text
•Press F7 to see your code window, and add the following code
15
to the Form1 Declarations area:
int inc, maxRows;
OleDbConnection con =new OleDbConnection();
DataSet ds = new DataSet();
OleDbDataAdapter da;
string sql;
When the Form Loads, we can connect to our database, use the data
Adaptor to grab some records from the database, and then put these
records into the DataSet.
So in the Form1 Load Event, add the following code:
con.ConnectionString = "provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\\CSE_DEPT.accdb";
con.Open();
16
sql = "SELECT * FROM student";
da = new OleDbDataAdapter(sql, con);
da.Fill(ds, "Studinfo");
con.Close();
maxRows = ds.Tables["Studinfo"].Rows.Count;
inc = -1;
To navigate through the records, the inc variable is used.
We'll either add 1 to it, or take 1 away. We'll then use the variable for the Rows in
the DataSet. It's better to do this in a Subroutine of your own.
private void NavigateRecords()
{
txtFirstName.Text =
Convert.ToString(ds.Tables["Studinfo"].Rows[inc].ItemArray[0]);
txtSurName.Text =
Convert.ToString(ds.Tables["Studinfo"].Rows[inc].ItemArray[1]);
}
17
The important part is Rows(inc). This moves us through the Rows
in the DataSet. We're then placing the values into the two Textboxes.
How to Move Forward One Record at a Time
Double click your Next Record button to access the code. Add the following If
… Else Statement
Add the code below and Run your program and click the button.
You should now be able to move forward through the DataSet. When you get to
the end, you should see the message box display "No More Rows".
if (inc != maxRows - 1)
{
inc = inc + 1;
NavigateRecords();
}
else
{ MessageBox.Show("No More Rows"); }
18
Move Back One Record at a Time
To move backwards through the DataSet, we need to decrement the inc
counter. All this means is deducting 1 from whatever is currently in inc.
Here's the code to add to your btnPrevious
if (inc > 0)
{ inc = inc - 1;
NavigateRecords();}
else if (inc == -1)
{
MessageBox.Show("No Records Yet");
}
else if (inc == 0)
{ MessageBox.Show("First Record"); }
19
Moving to the Last Record in the DataSet
To jump to the last record in the DataSet, you only need to know how
many records have been loaded into the DataSet - the MaxRows variable
in our code. Here's the code to add to your btnLast.
if (inc != maxRows - 1)
{inc = maxRows - 1;
NavigateRecords();}
Moving to the First Record in the DataSet
To move to the first record we need to set the inc counter to zero, if it's not
already at that value. Add the code on next slide to your btnFirst
if (inc != 0)
{inc = 0;
NavigateRecords();
}
20
Before we start the coding for these new buttons, it's important to
understand that the DataSet is disconnected from the database.
What this means is that if you're adding a new record, you're not
adding it to the database: you're adding it to the DataSet!
Similarly, if you're updating or Deleting, you are doing it to the
DataSet, and NOT to the database.
After you have made all of your changes, you THEN should commit
these changes to the database.You do this by issuing a separate
command.
Add a few more buttons to your form – five. Change the Name properties
of the new Buttons to the following: btnAddNew, btnCommit, btnUpdate,
btnDelete, btnClear
21
Change the Text properties of the buttons to "Add New Record
", “Commit Changes",
"Update Record ",
"Delete Record",
and "Clear".
22
DataTable tbladdress;
DataRow drCurrent;
tbladdress = ds.Tables["Studentinfo"];
drCurrent = tbladdress.NewRow();
drCurrent["FirstName"] = txtFirstName.Text;
drCurrent["Surname"] = txtSurName.Text;
tbladdress.Rows.Add(drCurrent);
MessageBox.Show("Add was successful.");
tbladdress = ds.Tables["Studentinfo"];
drCurrent =
tbladdress.Rows.Find(Convert.ToDouble(txtSearch.Text));
drCurrent.BeginEdit();
drCurrent["FirstName"] = txtFirstName.Text;
drCurrent.EndEdit();
MessageBox.Show("Record edited successfully");
27
When you do, you'll see a screen welcoming you to the Data
Source Configuration Wizard, Just click Next, to get to the screen
below:
Next to completing
data source wizard, you
have to tell the Wizard
where your database is.
28
So click the Browse button, and navigate to where on your
computer you saved the Database. Then click Next.
The Wizard will then take a look at your database, and display all
your tables, fields and objects.
Click the Tables box,
and all of the other items
will have ticks in them.
Notice the DataSet Name:
AddressBookDataSet.
You'll learn just what a
DataSet is in a later
section.
For now, just click the
Finish button.
29
When you click Finish, the Wizard goes to work. When it's done,
it looks as though not much has changed. But notice the Solution
Explorer:
The Data Sources area of the Solution Explorer now displays
information about your database.
Click the plus symbol next to
tblContacts
All the Fields in the AddressBook
database are now showing.
30
The fields from the database were then available to you in C# .NET.
In this part, we'll see how to construct a form so that you can see
and scroll through the data.
In the last part, you had the Data Sources window displayed. This
one (if you can't see the window, click Data from the menu bar.
Then click Show Data Sources)
To add a Field to your Form, click on one in the list. Hold down
your left mouse button, and drag it over to your form:
When your Field is over the Form, let go of your left mouse button.
A textbox and a label will be added.
There‘re two other things to notice: a navigation bar appears at the
top of the form, and a lot of strange objects have appeared in the
object area at the bottom:
31
We'll explore the Objects in a later section. But notice the
Navigation bar in blue.
Drag and Drop more Fields to your form and you have the following
interface.
Run your program by pressing the F5.
32
33
Example
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace WindowsFormsApplication20
{ public partial class frmDatabase : Form
{ public frmDatabase()
{ InitializeComponent(); }
int inc, maxRows;
OleDbConnection con =new OleDbConnection();
DataSet ds;
OleDbDataAdapter da;
string sql;
DataTable tblAddress;
DataRow drCurrent;
private void frmDatabase_Load(object sender, EventArgs e)
{con.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0; Data
Source=C:\\AddressBook.mdb";
con.Open();
ds =new DataSet();
sql = "SELECT * FROM student";
da = new OleDbDataAdapter(sql, con);
da.Fill(ds, "Studinfo");
con.Close();
maxRows = ds.Tables["Studinfo"].Rows.Count;
inc = -1; }
private void NavigateRecords()
{ txtFirstName.Text =
Convert.ToString(ds.Tables["Studinfo"].Rows[inc].ItemArray[0]);
txtSurName.Text =
Convert.ToString(ds.Tables["Studinfo"].Rows[inc].ItemArray[1]); }
private void btnNext_Click(object sender, EventArgs e)
{ if (inc != maxRows - 1)
{ inc = inc + 1;
NavigateRecords(); }
else
{ MessageBox.Show("No More Rows"); } }
private void btnPrevious_Click(object sender, EventArgs e)
{ if (inc > 0)
{ inc = inc - 1;
NavigateRecords();}
else if (inc == -1)
{ MessageBox.Show("No Records Yet");}
else if (inc == 0)
{ MessageBox.Show("First Record"); } }
private void btnLast_Click(object sender, EventArgs e)
{ if (inc != maxRows - 1)
{inc = maxRows - 1;
NavigateRecords();} }
private void btnFirst_Click(object sender, EventArgs e)
{ if (inc != 0)
{inc = 0_;
NavigateRecords(); }}
private void btnUpdate_Click(object sender, EventArgs e)
{ tblAddress = ds.Tables["Studentinfo"];
drCurrent = tblAddress.Rows.Find(Convert.ToDouble(txtSearch.Text));
drCurrent.BeginEdit();
drCurrent["FirstName"] = txtFirstName.Text;
drCurrent.EndEdit();
MessageBox.Show("Record edited successfully");}
private void btnAdd_Click(object sender, EventArgs e)
{ tblAddress = ds.Tables["Studentinfo"];
drCurrent = tblAddress.NewRow();
drCurrent["FirstName"] = txtFirstName.Text;
drCurrent["Surname"] = txtSurName.Text;
tblAddress.Rows.Add(drCurrent);
MessageBox.Show("Add was successful."); }
private void btnDelete_Click(object sender, EventArgs e)
{ if (MessageBox.Show("Do you really want to Delete this
Record?", "Delete", MessageBoxButtons.YesNo,
MessageBoxIcon.Warning) == DialogResult.No)
{ MessageBox.Show("Operation Cancelled"); }
else
{ tblAddress = ds.Tables["Studentinfo"];
drCurrent = tblAddress.Rows.Find(txtSearch.Text);
drCurrent.Delete();
MessageBox.Show("Record deleted successfully"); }}
private void btnSave_Click(object sender, EventArgs e)
{
OleDbCommandBuilder cb=new
OleDbCommandBuilder(da);
da.Update(ds, "Studentinfo");
MessageBox.Show("Updated successfully");}}}