Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I connect to a database and loop over a recordset in C#?

What's the simplest way to connect and query a database for a set of records in C#?

like image 879
Michael Pryor Avatar asked Aug 04 '08 00:08

Michael Pryor


1 Answers

@Goyuix -- that's excellent for something written from memory. tested it here -- found the connection wasn't opened. Otherwise very nice.

using System.Data.OleDb; ...  using (OleDbConnection conn = new OleDbConnection()) {     conn.ConnectionString = "Provider=sqloledb;Data Source=yourServername\\yourInstance;Initial Catalog=databaseName;Integrated Security=SSPI;";      using (OleDbCommand cmd = new OleDbCommand())     {         conn.Open();         cmd.Connection = conn;         cmd.CommandText = "Select * from yourTable";          using (OleDbDataReader dr = cmd.ExecuteReader())         {             while (dr.Read())             {                 Console.WriteLine(dr["columnName"]);             }         }     } } 
like image 69
Leon Bambrick Avatar answered Oct 14 '22 07:10

Leon Bambrick