Sei sulla pagina 1di 8

ADO.NET ----------Introducing Databases -------------------------Database in simple terms means a collection of structured information.

D atabases can store data in an organized and structured manner to facilitate the retrieval of data as and when required. A collection of records, that is rows, where each column is a field, bec omes a table. In its most common form, a database is just a collection of one or more tables. A simple collection of tables is a certain type of a database. DataSource communication --------------------------------Datasource is a place where we store the information which can be either a file or a database. While developing applications, information has to be stor ed under these data sources. But there is no language available, which can commu nicate with the data source directly, because each data source adopts a differen t protocol for communication. To overcome this problem, Microsoft provides a solution with two differe nt components like DRIVERS and PROVIDERS. These components act as mediators betw een the application and the datasource. Originally, when the need of data source communication was needed, Micro soft provided the solution in the form of DRIVERS to communicate with the databa se. These drivers are of two types 1. JET drivers Expanded as Joint Engine Technology drivers. These are designed for comm unicating with the local database such as Foxpro, dbase etc. 2. ODBC drivers Open Database Connectivity Drivers are designed for communicating with r emote databases, such as Oracle, SQL*Server etc. The major disadvantage with ODBC drivers is that the drivers hav e to be installed on the system, where the application is running and then confi gure with the application. To overcome the above drawback of ODBC drivers, OLEDB providers were int roduced. OLE DB (Object Linking and Embedding Database) providers are also desig ned for communicating with the data sources. OLEDB providers are a part of your application and do not require any separate installations and configurations lik e ODBC drivers. The drawback with drivers and providers is that - as they are designed w ith the native code language, they lead to platform dependency. In the traditional days, the language Visual Basic from Microsoft was no t capable of communicating with the native code drivers and providers. To overco me this problem, Microsoft developed some intermediate components which helps VB language to communicate with drivers and providers. These components are DAO (D ata Access Objects), RDO (Remote Data Objects) and ADO (ActiveX Data Objects). ADO.NET ----------When Microsoft launched .NET, the drivers and providers could not be use d for .NET application development, because they were O.S. dependent. Hence, out of the three components DAO, RDO and ADO, Microsoft picked up ADOs and re-imple mented it for you as ADO.NET(ActiveX Data Objects). ADO.NET is a collection of m anaged providers used for data source communication. .NET Framework Data Providers ---------------------------------------The data providers are used for connecting to a database, executing comm ands and also retrieving results. The data provider in ADO.NET consists of four main objects. 1. Connection

2. Command 3. DataReader 4. DataAdapter Connection -------------The 'Connection' object is used to connect to the data source. The base class for all the Connection objects is "DbConnection" class. The .NET framework provides two types of connection classes namely i) SqlConnection : designed to connect to Microsoft SQL Server. ii) OleDbConnection : designed to provide connections to a wide range of databas es such as Ms-Access and Oracle. Command -----------The 'Command' object is used to execute a command against a data source and retrieve a 'DataReader' or a 'DataSet'. It helps you in executing the INSERT , UPDATE or DELETE command against the data source. The base class for all the C ommand objects is "DbCommand". The .NET framework provides two types of command classes namely i) SqlCommand : designed to execute commands against an SQL Server database. ii) OleDbCommand : designed to execute commands against Ms-Access, Oracle etc. DataReader -------------The 'DataReader' provides a forward-only and read-only connected results et, using/from which you can read the corresponding rows. The base class is "Dat aReader". DataAdapter --------------The 'DataAdapter' object is used to update the 'DataSet' with data from the corresponding data source. The base class for all the 'DataAdapter' objects is "DbDataAdapter" class. The following are the list of data providers available. a) .NET framework data provider for SQL Server. Provides access to SQL*Server. Available in the namespace "System.Data.S qlCient". b) .NET framework data provider for OLEDB. Provides access to data soruces exposed by using OLEDB. Available in the namespace "System.Data.OleDb". c) .NET framework data provider for ODBC. Provides access to data sources exposed by using ODBC. Available in the namespace "System.Data.Odbc". d) .NET framework data provider for Oracle. Provides access to Oracle data source through Oracle client connectivity software. Available in the namespace "System.Data.OracleClient". Connection Strings ---------------------A connection string contains the initialization information that is pass ed as a parameter from the data provider to the data source. The "DbConnectionSt ringBuilder" is the base class for creating connection strings. The syntax of the connection string depends on the data provider. Once t he syntax of the connection string is validated, the data source opens the conne ction. You can get or set the connection string using the property "ConnectionSt

ring". The basic syntax of a connection string includes a series of keywords se parated by semi-colons. The "=" sign connects each keyword with its value. The v alue must be enclosed within double quotations. The syntax for each connection s tring is different for the data sources. Working with OLEDB providers ------------------------------------Connection String for Ms-Access ---------------------------------------In order to work out with Ms-Access, you must first create a connection string. The connection string consists of two keywords namely a) Provider Specifies the type of database that you want to connect to. To connect to Ms-A ccess, you can use the provider "Microsoft.Jet.OLEDB.4.0". b) Data Source Represents the path of the database file stored in your machine. Eg : "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\\C#1015\\Catalogue.mdb"; OleDbConnection class ---------------------------The 'OleDbConnection' class helps you to create a connection object. Constructor -------------i) OleDbConnection(); ii) OleDbConnection(String connectionString); Properties ------------a) ConnectionString Allows you to create a connection string. b) State Returns the current state of the connection. Methods ---------a) BeginTransaction() Starts a transaction. b)void Close() Closes the database connection. c)void Open() Opens the database connection. d) OleDbCommand CreateCommand(); Creates an 'OleDbCommand' object. OleDbCommand class ------------------------The 'OleDbCommand' class allows you to create a 'Command' object, using which you can issue commands against the data source. Constructors --------------i) OleDbCommand(); ii) OleDbCommand(string cmdText); iii) OleDbCommand(string cmdText, OleDbConnection object); Properties -----------i) Connection Allows you to specify the connection object to be used. ii) CommandText Allows you to specify the SQL command (INSERT, DELETE, UPDATE). Methods

---------i) Cancel() Tries to cancel the command. ii) int ExecuteNonQuery(); Executes the SQL statement against the connection and returns the number of row s affected. iii) object ExecuteScalar(); Returns a single value from a database query. iv) OleDbDataReader ExecuteReader(); Returns a resultset by the way of a 'DataReader' object. private void button1_Click(object sender, EventArgs e) { OleDbConnection con = new OleDbConnection(); con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source =F:\\C#1015\\Catalogue.mdb"; con.Open(); MessageBox.Show(con.State.ToString()); } OleDbDataReader class ----------------------------The 'OleDbDataReader' class gives you a way of reading a forward-only st ream of data rows from a database. Because this stream is "forward-only", you ca n read rows only one after the other. You cannot choose any row you want, or go backward. Data readers are low-level objects that give you a direct access to th e data in a database. To create an 'OleDbDataReader' object use the 'ExecuteRead er()' method of the 'OleDbCommand' object. Properties ------------i) FieldCount Gets the number of columns available in the current row. Methods ---------i) void Close() Closes the DataReader object. ii) bool Read() Advances the pointer to the next row in the table. iii) bool GetBoolean(int index); iv) byte GetByte(int index); v) char GetChar(int index); vi) decimal GetDecimal(int index); vii) double GetDouble(int index); viii) float GetFloat(int index); ix) short GetInt16(int index); x) int GetInt32(int index); xi) long GetInt64(int index); xii) string GetString(int index); xiii) object GetValue(int index); Retrieves the value out of the specified index. Working with the .NET framework data provider for ODBC -------------------------------------------------------------Provides access to data sources exposed by using ODBC. Available in the namespace "System.Data.Odbc". Using this namespace, you can access a wide range of databases such as Ms-Access, Oracle etc. The classes include -

i. OdbcConnection ii. OdbcCommand iii. OdbcDataReader iv. OdbcDataAdapter Creating a connection string ----------------------------------The connection string for an ODBC connection takes the following keyword s. i) DSN Specifies the Data Source Name created from the ODBC Manager. ii) UID Specifies the underlying user name. iii) PWD Specifies the password for the user. Procedure to create a DSN --------------------------------1. Select Start -> Settings -> Control Panel -> Administrative Tools -> Data Sou rces (ODBC). 2. Double click on it. It opens the Microsoft ODBC Data Source Administrator. 3. Click on the button "Add". It displays the list of drivers available. 4. Select the driver related to Oracle / Ms-Access and click on the button "Fini sh". 5. Specify a name for the connection using the option "Data Source Name". Then s pecify the user name related with Oracle using the option "User Id". 6. Click on the button "Test Connection". In the authentication dialog specify t he "user name" and "password" and click on the button "Test Connection" to check if the connection works out or not. 7. Ultimately click on the button "Ok". Working with .NET framework data provider for SQL Server ----------------------------------------------------------------Provides access to SQL*Server. Available in the namespace "System.Data.S qlCient". This provider again provides us with 4 classes namely 1. SqlConnection 2. SqlCommand 3. SqlDataReader 4. SqlDataAdapter Working with Microsoft SQL Server 2005 -------------------------------------------------SQL Server is the default database for .NET. To work out with SQL Server , first of all you need to install SQL Server into your machines. To work with S QL Server it provides a 'Development Management Studio' using which you can inte ract with the database. Connecting to SQL Server 2005 --------------------------------------1. Start the SQL Server Management Studio. It provides the following authenticat ion screen. Fig.1 2. Use the following options a) Server Type - Database Engine b) Server Name - Specifies the name of the machine. c) Authentication - Specifies the user authentication. There are 2 types of auth entication i) Windows Authentication In Windows Authentication, you need not specify the user name and passwo

rd. ii) SQL Server Authentication In SQL Server Authentication, you specify the user name which is "sa" by default and then you specify the password (password set during installation of SQL Server). 3. After specifying the above options, click on the button "Connect". It connect s you to the SQL Server Database. Creating Tables ------------------1. In the 'Object Explorer' window, expand the tree Databases -> System Database s -> master -> Tables. 2. Select the option 'Tables' and right click on it. 3. It displays a context menu, from which select the menu option "New Table". 4. It then invokes the 'Table structure' on the right window, where you can spec ify the required column names along with their data-types. After specifying the columns close the window. 5. It then prompts you for the name of the table. Specify a table name and click on the button 'Save'. (or) Alternatively, you can also create tables using the sql statement 'CREATE TABLE' . Use the following steps. 1. In the toolbar, click on the button "New Query". 2. On the right hand side it opens a file with the extension .sql. 3. Type your required query in it. For example ---------------create table books (book_id int, book_name varchar(50), author varchar(50), category varchar(50), cost int, copies int); 4. To execute the query, you will find the button "Execute" on the toolbar itsel f. 5. Click on the button to execute the query. CREATING A CONNECTION STRING FOR SQL SERVER ---------------------------------------------------------------The connection string for SQL Server includes the following parameters a) Data Source Represents the name or the network address of the instance of the SQL Server to which you want to connect. b) Initial Catalog Represents the name of the database in SQL Server to which you want to connect.

c) Integrated Security Accepts two values - True or False. If the value is 'False', then you need to s pecify the user id and password. If the value is 'True', then the current Window s accounts credentials are used for authentication. The default is 'True'. For example : -----------------"Data Source=system-name;Initial Catalog=master;Integrated Security=True"; public partial class Form1 : Form { SqlConnection con; SqlCommand cmd; SqlDataReader reader; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { con = new SqlConnection(); con.ConnectionString = "Data Source=PATRICKS;Initial Catalog=master; Integrated Security=True"; con.Open(); MessageBox.Show(con.State.ToString()); } private void button2_Click(object sender, EventArgs e) { /* cmd = new SqlCommand(); cmd.Connection = con; cmd.CommandText = "select * from users where user_name='" + textBox1 .Text + "' and password='" + textBox2.Text + "'"; reader = cmd.ExecuteReader(); if (reader.Read()) { MessageBox.Show("Valid user with a valid password"); } else { MessageBox.Show("Invalid user or Invalid password"); } reader.Dispose(); cmd.Dispose(); */ cmd = new SqlCommand(); cmd.Connection = con; cmd.CommandText = "select * from users"; reader = cmd.ExecuteReader(); string uid, pwd; int count=0; while (reader.Read()) { uid = reader.GetValue(0).ToString(); if (uid == textBox1.Text) { pwd = reader.GetValue(1).ToString();

if (pwd == textBox2.Text) { count = 1; MessageBox.Show("Valid user with a valid password"); break; } else { count = 1; MessageBox.Show("Invalid password !"); textBox2.Focus(); break; } } } if (count == 0) { MessageBox.Show("Invalid username"); textBox1.Focus(); } cmd.Dispose(); reader.Dispose(); } } SDI/MDI Applications -------------------------An SDI (Single Document Interface) application is one in which you can o pen only one document at a time. The best example for an SDI application is a "N otepad". On the other hand a MDI (Multiple Document Interface) application is one in which a user can open more than one document simultaneously. The best exampl e for an MDI application is Ms-Word. In an MDI application, you have a parent wi ndow in which the child windows are embedded. The parent window does not allow t he child window to move out of its boundaries. Creating an MDI parent window --------------------------------------To create an MDI parent window, first of all open a 'Windows Forms Appli cation' Project. This project by default adds a form with the name "Form1". Now to make this form an MDI parent window, invoke the 'Properties' dialog box and s et the property "IsMdiContainer" to "True". This makes the form an MDI parent wi ndow. Creating an MDI Child window ------------------------------------Once a parent window has been created, you can then create a child windo w for the parent window. To do so, first of all add a new form to your applicati on using the menu option Project -> Add Windows Form. You can add as many forms as you want. Once added, the newly added form can be set as a child to the paren t window using the property "MdiParent". Set the name of the MDI Form to the "Md iParent" property.

Potrebbero piacerti anche