A brief description of the three core objects of ADO. net

Source: Internet
Author: User

SqlConnection // connection string

SqlCommand // the object for executing SQL commands

SqlDataReader // read records from the database

Note that you must disable DataReader even if you disable SqlConnection. Otherwise, an error will occur when you use unclosed DataReader next time.

The sample code is as follows:

Demo
Class Program
{

/// <Summary>
/// Application entry
/// </Summary>
/// <Param name = "args"> </param>
/// <Returns> </returns>
Static void Main (string [] args)
{
String connectionString = GetConnectString ();
String queryString = "select * from person where id = 2 ";
// String queryString = "delete from person where id = 2 ;";
Using (SqlConnection connection = new SqlConnection (connectionString ))
{
SqlCommand command = connection. CreateCommand ();
Command. CommandText = queryString;
Command. CommandType = CommandType. Text;

Try
{
Connection. Open ();
// Command. ExecuteNonQuery (); // execute a non-query command
SqlDataReader reader = command. ExecuteReader () // read data command;
While (reader. Read ())
{
For (int I = 0; I <reader. FieldCount; I ++)
{
Console. Write ("{0} \ t", reader [I]);
}
Console. writeline ();
}
Reader. Close ();
}
Catch (System. Exception ex)
{
Console. WriteLine (ex. Message );
}
}
Console. Read ();
}

/// <Summary>
/// Connection string
/// </Summary>
/// <Returns> </returns>
Public static string getconnectstring ()
{
Return "Data Source = (local); init ial catalog = mytestdb ;"
+ "Integrated Security = sspi ";
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.