VisualBuilder
  Home > Csharp > Tutorials > Database Interaction Using C sharp - C# Tutorial
Tell a friend
Link to us
Total Members
      Members: 84606
     
Sitemap Forum Chat
Home
C# Tutorial Home
1 . Introduction to C sharp
2 . Control Statement: Selection Statement in C sharp
3 . Control Statements – Loops Statement
4 . Methods
5 . Namespaces
6 . Introduction to Classes:
7 . Inheritance:
8 . Polymorphism
9 . Properties
10 . Indexers
11 . Structs
12 . Interfaces
13 . Delegates:
14 . Exception Handling:
15 . Attributes
16 . Enums
17 . Encapsulation
18 . Parameter Passing in C sharp
19 . Method Overloading
20 . Database Interaction Using C sharp
21 . Operator Overloading in C sharp -1
22 . Operator Overloading in C sharp -2
23 . Operator Overloading in C sharp -2
24 . Sockets
25 . DNS [Domain Name System]
26 . Working with Files
27 . Generating Help File in C sharp
28 . Code Access Security
29 . Multi-Threading
30 . Globalization and Localization -1
31 . Working with Registry in C sharp
32 . Globalization and Localization -2
33 . Windows Service
34 . Web Service
35 . Consuming Web Services
36 . Creating Proxy Object of Web Service
37 . Creating an XML document
38 . Reading XML document in C sharp
39 . Using XMLWriter class to Write XML document in C sharp
40 . Assembly Information : Getting Permission set of the assembly
41 . Creating your own Permission Set
42 . Using C sharp Socket
 
Csharp Group Home
Csharp Discussion (7)
Csharp Members (2250)
Csharp Resources
Csharp Source Code (35)
Csharp Articles (0)
Csharp Blogs
Csharp Jobs
Csharp Components (5)
Csharp Books
Csharp Websites (25)
Csharp News (17)
Csharp Q & A (4)
- Csharp Ask Question
- Csharp Questions
- Csharp Unanswered Questions
 
GROUPS
.NET
ASP.NET
.NET
C#
ASP
Visual Basic
Java
Java
JSP
EJB
Other
Delphi
C++
Ajax
UML
JavaScript
PHP
Web Design
Web Hosting
SQL Server
Oracle
Project Management
More Groups

 
LEARNING CENTER
TUTORIALS
.NET
.NET Tutorial
ASP Tutorial
ASP.NET Database Tutorial
ASP.NET Development Tips
ASP.Net Security,Internationalisation And Deployment
ASP.NET Server Controls Tips
ASP.NET Tutorial
C Sharp Tutorial
Web Development
Flex Tutorial
HTML Tutorial
Learn AJAX Tutorial
PHP Tutorial
Software Development
Database Tutorial
SQL Tutorial
UML Tutorial
Java
Ant Tutorial
EJB 3 Tutorial
Hibernate Tutorial
Java Tutorial
Java Web Component Tutorial
Java XML Tutorial
JDBC Tutorial
JDK1.5 Tutorial
JSF Tutorial
JSP And J2EE Design Tutorial
JSP Tutorial
Spring Tutorial
Struts Tutorial

RESOURCES
Q & A (432 )
Source Code (3217 )
Articles (11 )
Components (1589 )
News (880 )
Websites (1207 )

SUBMISSIONS
Submit Article
Submit Website
Submit News
Submit Source Code
Submit Component

COMMUNITY
Members Directory
Discussion Forum
Chat

SITE
About Us
Sitemap
Search
Contact Us
Link To Us
Feedback
Tell a Friend
Partners
Advertise


Csharp Tutorial
 Database Interaction Using C sharp
  << Prev: Method Overloading Next: Operator Overloading in C sharp -1 >>

C# is a language. The classes defined in the class libraries are used to communicate with the database and we are using C# language to interact with the database. In Ado.Net components we have number of classes that are responsible to communicate with the database.


 


Introducing ADO.NET


 


Ado.Net is an Object-oriented set of libraries that allows you to interact with data sources. Following are the data providers in ado.net.



  1. System.Data.SqlClient:- contains classes that communicate with Ms SQLServer.

  2. System.Data.OracleClient:- communicate with Oracle.

  3. System.Data.Oledb:- communicate to a data source that has an OLEDB provider.

  4. System.Data.Odbc:- communicate to a data source that has an ODBC provider


ADO.NET OBJECTS


Ado.net includes many objects you can use to work with data. Some of the primary objects are as follows:-



  1. SqlConnection:- To interact with a database, you must have a connection to it. The connection objects helps identifying the database server, database name, user name and password. The connection object is used by command objects.

  2. SqlCommand:- You can use this object to send SQL statements to the database. This can represent a SQL Statement or stored procedure.

  3. SqlDataReader:- The data reader object allows you to obtain the results of a Select statement from a command object. The data returned from a data reader is a fast forward-only stream of data. This fetch data in a sequential manner.

  4. DataSet:- You can imagine dataset as a database. This contain multiple datatable objects, which further contains columns and rows objects. We can also define relationship among tables in the dataset. This is disconnected approach.

  5. SqlDataAdapter:- The SqlDataAdapter is used to fill dataset object when reading the data and writes in a single batch when persisting changes back to the database. A data adapter contains a reference to the connection object and opens and closes the connection automatically when reading from or writing to the data base. The data adapter contains 4 command objects i.e. SELECT, UPDATE, DELETE, and INSERT


Example: Demonstrate Database Interaction


 


This example will provide the interaction with the database. The user will enter his credentials, if the user is valid and the credentials matched with the database, he is able to view all the other users' credentials that are valid.


 




 


 


Form20.cs


 


using System;


using System.Collections.Generic;


using System.ComponentModel;


using System.Data;


using System.Drawing;


using System.Text;


using System.Windows.Forms;


using System.Data.SqlClient;


 


namespace cSHARPEXAMPLES


{


  public partial class Form20 : Form


    {


    public Form20()


        {


            InitializeComponent();


        }


    private void btnLogin_Click( object sender, EventArgs e)


        { //Login


      try


            {


                SqlConnection con = null ;


                string conStr = "" ;


                int _ExistFlag = 0;


                conStr = "Data Source=localhost;initial catalog=TestDB;uid=sa;pwd=sa" ;


        con = new SqlConnection (conStr);


        _ExistFlag = fnUserExists(con,txtName.Text,txtPassword.Text);


            if (_ExistFlag == 0)


                { //Not A Valid User


          MessageBox .Show( "Not A Valid User" );


                }


        else


                { // If Valid user Than Display all the Valid User that are there in the DataBase


          MessageBox .Show( "Valid User :: Display All the Valid User" );


                    fillgridWithValidUser(con);


                }


            }


      catch ( Exception ex)


            {


        MessageBox .Show( "Exception Occurs.........." +ex.Message);


            }


      finally


            {


        txtName.Text = "" ;


        txtPassword.Text = "" ;


            }


        }


 


    /*


    * Function: Whether a Valid User or Not


    * Depending on the creadentials enter by user


    */


    private int fnUserExists( SqlConnection con, string strUserName, string strPassword)


        {


          SqlCommand cmd = null ;


          int _ExistFlag = 0;


          cmd = new SqlCommand ( "select count(*) from tblLogin where UserName=@UserName and password=@Password " , con);


          cmd.Parameters.Add( "@UserName" , SqlDbType.NVarChar).Value = strUserName;


          cmd.Parameters.Add( "@Password" , SqlDbType.NVarChar).Value = strPassword;


          cmd.CommandType = CommandType .Text;


          con.Open();


      _ExistFlag = Int16 .Parse(cmd.ExecuteScalar().ToString());


          con.Close();


      return _ExistFlag;


          }


 


    /*


    * if the Credentials Enter By user is Valid:


    * Then Display List Of all The Other Valid Users.


    */


    private void fillgridWithValidUser( SqlConnection con)


        {


          SqlDataAdapter ada = null ;


          DataSet dst = null ;


          ada = new SqlDataAdapter ( "select * from tblLogin" , con);


          dst = new DataSet ();


          ada.Fill(dst, "Login" );


        dataGridView1.DataSource = dst.Tables[0].DefaultView;


        }


    }


}


 


Output:


 


On Click: Login Button


 




 




 


 


  << Prev: Method Overloading Next: Operator Overloading in C sharp -1 >>
Csharp Tutorial Home
Give feedback and win a prize.

 
   Printer Friendly
   Email to a friend
   Add to my Favourites    
  Download PDF version
   Report Bad Submissions
   Submit Feedback
 
  Delicious   Digg   Technorati   Blink   Furl   Reddit   Newsvine   Google Click each image to add
this page to each site.
 
 
Welcome Guest Signup
MEMBER'S PANEL
EMAIL
PASSWORD
Forgot your password?
New User? Click Here!
 
Resend Activation Email!
 
SEARCH
 
 
LINKS
MSN
Video Surveillance
VoIP Internettelefonie AT
Gift to Pakistan
 
ADVERTISEMENT
 
PARTNER LIST

More
 
 
 

Home | Login | About Us | Contact Us | Privacy Policy | Advertising