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 ";
}