C # console create a database connection

And connection to the database mainly in the following three types:

sqlconnection: database connection class;

sqlcommand: database operation;

sqldatareader: reading database;

DR = cmd.ExecuteReader the SqlDataReader ();
dr.hasrows: whether data;
dr.Read: read pointer down data;
dr.fieldcount: Get number of columns in the result set;
dr.getname; Gets column name specified column;

 

// Create a class object database connected to
  the SqlConnection the SqlConnection Conn new new = ( "Database Server .; = = mydb; ?? = User; password = ??");
  the SqlCommand cmd = conn.CreateCommand (); // Create operation target according to the connection ;
  cmd.CommandText = "SELECT * from Fruit"; // write t-sql statement;

  conn.Open (); // open connection;
  the SqlDataReader cmd.ExecuteReader DR = (); // perform reading method, data is read , dr returns the result set; and send to the connection CommandText production Reader;

  the while (dr.Read ())
  {
    //Console.Write(dr["ids"].ToString()+ "" + dr [ "name"] .ToString () + "\ n-");
    for (int I = 0; I <dr.FieldCount; I ++) // number of columns dr.fieldcount;
    {
      Console.Write (DR [I] + "");
    }
    Console.Write ( "\ the n-");
    // foreach can not be used

  }

  conn.Close (); // close the connection;
  Console.ReadLine ();

Guess you like

Origin www.cnblogs.com/kinn/p/11090108.html