Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » ADO.NET & Database » Real Life SQL and .NET :Using SQL with C#: Part VIII

Real Life SQL and .NET :Using SQL with C#: Part VIII

Welcome to the world of SQL and the huge, growing database technologies of today’s business all over the SQL world. By reading this article, we have begun accepting the knowledge that will soon be required for survival in today’s world of relational database and data management. Alas, for the reason that it is first necessary to provide a background of SQL and cover some preliminary concepts that we need to know, the majority of this article is text in paragraph format.

Author Rank :
Page Views : 30456
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Nevron Chart
Become a Sponsor
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Using SQL with C#

A .NET data provider describes a collection of classes used to access a data source, such as a database, in the managed space. Using the OleDbDataAdapter, you can fill a memory-resident DataSet, which you can use to query and update the datasource.

Classes

 

 

 


 

 

 

 



 

Class
Description.
OleDbCommand
Represents an SQL statement or stored procedure to execute against a data source.
OleDbCommandBuilder
Provides a means of automatically generating single-table commands used to reconcile changes made to a DataSet with the associated database. This class cannot be inherited.
OleDbConnection
 Represents an open connection to a data source.
OleDbDataAdapter

 Represents a set of data commands and a database connection that are used to fill the DataSet and update the data source.
OleDbDataReader
Provides a way of reading a forward-only stream of data rows from a data source. This class cannot be inherited.
OleDbError
Collects information relevant to a warning or error returned by the data source. This class cannot be inherited.
OleDbErrorCollection
Collects all errors generated by the OLE DB .NET Data Provider. This class cannot be inherited.
OleDbException
The exception that is thrown when the underlying provider returns a warning or error for an OLE DB data source. This class cannot be inherited.
OleDbInfoMessageEventArgs
Provides data for the InfoMessage event. This class cannot be inherited.
OleDbParameter
Represents a parameter to an OleDbCommand and optionally, its mapping to a DataSet column. This class cannot be inherited.
 
OleDbParameterCollection
Collects all parameters relevant to an OleDbCommand as well as their respective mappings to DataSet columns.
OleDbPermission
 Provides the capability for the OLE DB .NET Data Provider to ensure that a user has a security level adequate to access an OLE DB data source.
OleDbPermissionAttribute
Associates a security action with a custom security attribute.
OleDbRowUpdatedEventArgs
Provides data for the RowUpdated event.
OleDbRowUpdatingEventArgs
Provides data for the RowUpdating event.
OleDbSchemaGuid
Returns the type of schema table specified by the GetOleDbSchemaTable method.
OleDbTransaction
Represents an SQL transaction to be made at a data source. This class cannot be inherited

Delegates

Delegate
Description
OleDbInfoMessageEventHandler
Represents the method that will handle the InfoMessage event of an OleDbConnection.
OleDbRowUpdatedEventHandler
Represents the method that will handle the RowUpdated event of an OleDbDataAdapter.
OleDbRowUpdatingEventHandler
Represents the method that will handle the RowUpdating event of an OleDbDataAdapter.
 

Enumerations

Enumeration Description
OleDbLiteral
Returns information about literals used in text commands, data values, and database objects.
OleDbType
Specifies the data type of a field, a property, or an OleDbParameter.

OleDbDataAdapter Class

Represents a set of data commands and a database connection that are used to fill the DataSet and update the data source. For a list of all members of this type, see OleDbDataAdapter Members.

System.Object
            System.MarshalByRefObject
            System.ComponentModel.Component
            System.Data.Common.DataAdapter
            System.Data.Common.DbDataAdapter
            System.Data.OleDb.OleDbDataAdapter

And syntax in C#:

public sealed class OleDbDataAdapter: DbDataAdapter, IDbDataAdapter;

Any public static members of this type are safe for multithreaded operations. Any instance members are not guaranteed to be thread safe. The OleDbDataAdapter serves as a bridge between a DataSet and data source for retrieving and saving data. The OleDbDataAdapter provides this bridge by using Fill to load data from the data source into the DataSet, and using Update to send changes made in the DataSet back to the data source.

When the OleDbDataAdapter fills a DataSet, it will create the necessary tables and columns for the returned data if they do not already exist. However, primary key information will not be included in the implicitly created schema unless the MissingSchemaAction property is set to AddWithKey. You may also have the OleDbDataAdapter create the schema of the DataSet, including primary key information, before filling it with data using FillSchema. Note that some OLE DB providers, including the MSDataShape provider, do not return base table or primary key information. As a result, the OleDbDataAdapter cannot properly set the PrimaryKey property on any created DataTable. In such cases you should explicitly specify primary keys for tables in the DataSet. The OleDbDataAdapter also includes the SelectCommand, InsertCommand, DeleteCommand, UpdateCommand, and TableMappings properties to facilitate the loading and updating of data.

When you create an instance of OleDbDataAdapter, properties are set to their initial values. For a list of these values, see the OleDbDataAdapter constructor. The following example uses the OleDbCommand, OleDbDataAdapter, and OleDbConnection, to select records from an Access data source, and populate a DataSet with the selected rows. The filled DataSet is then returned. To accomplish this, the method is passed an initialized DataSet, a connection string, and a query string that is a SQL SELECT statement.

public DataSet SelectOleDbSrvRows(DataSet dataset,string connection,string query)
{
OleDbConnection conn =
new
OleDbConnection(connection);
OleDbDataAdapter adapter =
new
OleDbDataAdapter();
adapter.SelectCommand =
new
OleDbCommand(query, conn);
adapter.Fill(dataset);
return
dataset;
}

Execute an SQL SELECT command in C#

When SelectCommand is assigned to a previously created OleDbCommand, the OleDbCommand is not cloned. The SelectCommand maintains a reference to the previously created OleDbCommand object. If the SelectCommand does not return any rows, no tables are added to the DataSet, and no exception is raised.

public void CreateOleDbDataAdapter ()
{
OleDbDataAdapter myDataAdapter =
new
OleDbDataAdapter();
myDataAdapter.SelectCommand.CommandText = "SELECT * FROM Categories ORDER BY
ategoryID";
myDataAdapter.SelectCommand.Connection.ConnectionString =
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=NWIND_RW.MDB";
}

System.Data.SqlClient Namespace

The System.Data.SqlClient namespace is the SQL Server .NET Data Provider. A .NET data provider describes a collection of classes used to access a SQL Server database in the managed space. Using the SqlDataAdapter, you can fill a memory-resident DataSet, which you can use to query and update the datasource. For information on how this namespace can help you, see the SqlDataAdapter, the SqlCommand, and the SqlConnection classes.

Classes

Class
Description
SqlClientPermission
Provides the capability for the SQL Server .NET Data Provider to ensure that a user has a security level adequate to access a data source.
SqlClientPermissionAttribute
Associates a security action with a custom security attribute.
SqlCommand
Represents a Transact-SQL statement or stored procedure to execute against a SQL Server database. This class cannot be inherited.
SqlCommandBuilder
Provides a means of automatically generating single-table commands used to reconcile changes made to a DataSet with the associated SQL Server database. This class cannot be inherited.
 
SqlConnection Represents an open connection to a SQL Server database. This class cannot be inherited.
 
SqlDataAdapter
Represents a set of data commands and a database connection that are used to fill the DataSet and update a SQL Server database. This class cannot be inherited.
SqlDataReader
Provides a means of reading a forward-only stream of rows from a SQL Server database. This class cannot be inherited.
SqlError
Collects information relevant to a warning or error returned by SQL Server. This class cannot be inherited.
SqlErrorCollection
Collects all errors generated by the SQL .NET Data Provider. This class cannot be inherited.
SqlException
 The exception that is thrown when SQL Server returns a warning or error. This class cannot be inherited.
SqlParameter
Represents a parameter to a SqlCommand, and optionally, its mapping to DataSet columns. This class cannot be inherited.
SqlParameterCollection
Collects all parameters relevant to a SqlCommand as well as their respective mappings to DataSet columns. This class cannot be inherited.
SqlRowUpdatedEventArgs
Provides data for the RowUpdated event. This class cannot be inherited.
SqlRowUpdatingEventArgs
Provides data for the RowUpdating event. This class cannot be inherited.
SqlTransaction
Represents a Transact-SQL transaction to be made in a SQL Server database. This class cannot be inherited.
SqlInfoMessageEventArgs
Provides data for the InfoMessage event. This class cannot be inherited.

Delegates

Delegate Description
SqlInfoMessageEventHandler
Represents the method that will handle the InfoMessage event of a SqlConnection.
SqlRowUpdatedEventHandler
Represents the method that will handle the RowUpdated event of a SqlDataAdapter.
SqlRowUpdatingEventHandler
Represents the method that will handle the RowUpdating event of a SqlDataAdapter.
 

SqlDataAdapter Class

Represents a set of data commands and a database connection that are used to fill the DataSet and update a SQL Server database. This class cannot be inherited. For a list of all members of this type, see SqlDataAdapter Members.

System.Object
            System.MarshalByRefObject
            System.ComponentModel.Component
            System.Data.Common.DataAdapter
            System.Data.Common.DbDataAdapter
            System.Data.SqlClient.SqlDataAdapter

public sealed class SqlDataAdapter : DbDataAdapter, IDbDataAdapter ;

Any public static members of this type are safe for multithreaded operations. Any instance members are not guaranteed to be thread safe. The SqlDataAdapter serves as a bridge between a DataSet and SQL Server for retrieving and saving data. The SqlDataAdapter provides this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source, and Update, which changes the data in the data source to match the data in the DataSet, using the appropriate Transact-SQL statements against the data source.

SqlDataAdapter is used in conjunction with SqlConnection and SqlCommand to increase performance when connecting to a Microsoft SQL Server database. To access other data sources, use OleDbDataAdapter along with its associated OleDbCommand and OleDbConnection. The SqlDataAdapter also includes the SelectCommand, InsertCommand, DeleteCommand, UpdateCommand, and TableMappings properties to facilitate the loading and updating of data.

When an instance of SqlDataAdapter is created, the read/write properties are set to initial values. For a list of these values, see the SqlDataAdapter constructor. The following example uses the SqlCommand, SqlDataAdapter, and SqlConnection, to select records from a data source, and populate a DataSet with the selected rows. The filled DataSet is then returned. To accomplish this, the method is passed an initialized DataSet, a connection string, and a query string that is a Transact-SQL SELECT statement.

public static void CreateSqlDataAdapter()
{
SqlConnection nwindConn = new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind");
SqlDataAdapter custDA = new SqlDataAdapter();
custDA.MissingSchemaAction = MissingSchemaAction.AddWithKey;
custDA.SelectCommand = new SqlCommand("SELECT CustomerID, CompanyName FROM CUSTOMERS", nwindConn);
custDA.InsertCommand = new SqlCommand("INSERT INTO Customers (CustomerID, CompanyName) " + "VALUES (@CustomerID, @CompanyName)", nwindConn);
custDA.UpdateCommand = new SqlCommand("UPDATE Customers SET CustomerID = @CustomerID, CompanyName = @CompanyName " + "WHERE CustomerID = @oldCustomerID", nwindConn);
custDA.DeleteCommand = new SqlCommand("DELETE FROM Customers WHERE CustomerID = @CustomerID", nwindConn);
custDA.InsertCommand.Parameters.Add("@CustomerID", SqlDbType.Char, 5, "CustomerID");
custDA.InsertCommand.Parameters.Add("@CompanyName", SqlDbType.VarChar, 40, "CompanyName");
custDA.UpdateCommand.Parameters.Add("@CustomerID", SqlDbType.Char, 5, "CustomerID");
custDA.UpdateCommand.Parameters.Add("@CompanyName", SqlDbType.VarChar, 40, "CompanyName");
custDA.UpdateCommand.Parameters.Add("@oldCustomerID", SqlDbType.Char, 5, "CustomerID").SourceVersion = DataRowVersion.Original;
custDA.DeleteCommand.Parameters.Add("@CustomerID", SqlDbType.Char, 5, "CustomerID").SourceVersion = DataRowVersion.Original;} 

SqlDataAdapter.SelectCommand Property

Gets or sets a Transact-SQL statement or stored procedure used to select records in the data source.

public new SqlCommand SelectCommand {get; set;}

A SqlCommand used during Fill to select records from the database for placement in the DataSet. When SelectCommand is assigned to a previously created SqlCommand, the SqlCommand is not cloned. The SelectCommand maintains a reference to the previously created SqlCommand object. If the SelectCommand does not return any rows, no tables are added to the DataSet, and no exception is raised. The following example creates a SqlDataAdapter and sets some of its properties.

public void CreateSqlDataAdapter()
{
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
myDataAdapter.SelectCommand.CommandText = "SELECT * FROM Categories ORDER BY CategoryID";
myDataAdapter.SelectCommand.Connection = new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind");
myDataAdapter.UpdateCommand.CommandText = "UPDATE Categories SET Description='Cheeses, Milk, Ice Cream' WHERE CategoryName='Dairy Products'";
myDataAdapter.UpdateCommand.Connection = (SqlConnection) myDataAdapter.SelectCommand.Connection;
}

continue article

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
John Hudai Godel
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Request by vijay On February 25, 2007
Dear John, Will u send me the page: Real Life SQL and .NET :Using SQL with C#: Part XI. Since i m unable to read this. and thanks, for this amazing tutorial.
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.