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

[{'answer_id': 940, 'author': 'Goyuix', 'author_id': 243, 'author_profile': 'https://Stackoverflow.com/users/243', 'pm_score': 4, 'selected': False, 'text': '<p>Very roughly and from memory since I don\'t have code on this laptop:</p>\n\n<pre><code>using (OleDBConnection conn = new OleDbConnection())\n{\n  conn.ConnectionString = "Whatever connection string";\n\n  using (OleDbCommand cmd = new OleDbCommand())\n  {\n    cmd.Connection = conn;\n    cmd.CommandText = "Select * from CoolTable";\n\n    using (OleDbDataReader dr = cmd.ExecuteReader())\n    {\n      while (dr.Read())\n      {\n        // do something like Console.WriteLine(dr["column name"] as String);\n      }\n    }\n  }\n}\n</code></pre>\n'}, {'answer_id': 951, 'author': 'Leon Bambrick', 'author_id': 49, 'author_profile': 'https://Stackoverflow.com/users/49', 'pm_score': 6, 'selected': True, 'text': '<p>@Goyuix -- that\'s excellent for something written from memory.\ntested it here -- found the connection wasn\'t opened. Otherwise very nice.</p>\n\n<pre><code>using System.Data.OleDb;\n...\n\nusing (OleDbConnection conn = new OleDbConnection())\n{\n    conn.ConnectionString = "Provider=sqloledb;Data Source=yourServername\\\\yourInstance;Initial Catalog=databaseName;Integrated Security=SSPI;";\n\n    using (OleDbCommand cmd = new OleDbCommand())\n    {\n        conn.Open();\n        cmd.Connection = conn;\n        cmd.CommandText = "Select * from yourTable";\n\n        using (OleDbDataReader dr = cmd.ExecuteReader())\n        {\n            while (dr.Read())\n            {\n                Console.WriteLine(dr["columnName"]);\n            }\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 1022, 'author': 'MojoFilter', 'author_id': 93, 'author_profile': 'https://Stackoverflow.com/users/93', 'pm_score': 4, 'selected': False, 'text': '<p>That\'s definitely a good way to do it.  But you if you happen to be using a database that supports LINQ to SQL, it can be a lot more fun.  It can look something like this:</p>\n\n<pre><code>MyDB db = new MyDB("Data Source=...");\nvar q = from db.MyTable\n        select c;\nforeach (var c in q)\n  Console.WriteLine(c.MyField.ToString());\n</code></pre>\n'}, {'answer_id': 2369, 'author': 'Marek Grzenkowicz', 'author_id': 95, 'author_profile': 'https://Stackoverflow.com/users/95', 'pm_score': 3, 'selected': False, 'text': '<p>This is an alternative way (DataReader is faster than this one):</p>\n\n<pre><code>string s = "";\nSqlConnection conn = new SqlConnection("Server=192.168.1.1;Database=master;Connect Timeout=30;User ID=foobar;Password=raboof;");\nSqlDataAdapter da = new SqlDataAdapter("SELECT TOP 5 name, dbid FROM sysdatabases", conn);\nDataTable dt = new DataTable();\n\nda.Fill(dt);\n\nfor (int i = 0; i &lt; dt.Rows.Count; i++)\n{\n    s += dt.Rows[i]["name"].ToString() + " -- " + dt.Rows[i]["dbid"].ToString() + "\\n";\n}\n\nMessageBox.Show(s);\n</code></pre>\n'}, {'answer_id': 20049, 'author': 'Christian Hagelid', 'author_id': 202, 'author_profile': 'https://Stackoverflow.com/users/202', 'pm_score': 2, 'selected': False, 'text': '<p>If you are querying a SQL Server database (Version 7 and up) you should replace the OleDb classes with corresponding classes in the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient" rel="nofollow noreferrer">System.Data.SqlClient</a> namespace (<a href="https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection" rel="nofollow noreferrer">SqlConnection</a>, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand" rel="nofollow noreferrer">SqlCommand</a> and <a href="https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldatareader" rel="nofollow noreferrer">SqlDataReader</a>) as those classes have been optimized to work with SQL Server.</p>\n\n<p>Another thing to note is that you should \'never\' select all as this might lead to unexpected results later on if you add or remove columns to this table.</p>\n'}, {'answer_id': 65774, 'author': 'DamienG', 'author_id': 5720, 'author_profile': 'https://Stackoverflow.com/users/5720', 'pm_score': 2, 'selected': False, 'text': '<p>If you are intending on reading a large number of columns or records it\'s also worth caching the ordinals and accessing the strongly-typed methods, e.g.</p>\n\n<pre><code>using (DbDataReader dr = cmd.ExecuteReader()) {\n  if (dr.Read()) {\n    int idxColumnName = dr.GetOrdinal("columnName");\n    int idxSomethingElse = dr.GetOrdinal("somethingElse");\n\n    do {\n      Console.WriteLine(dr.GetString(idxColumnName));\n      Console.WriteLine(dr.GetInt32(idxSomethingElse));\n    } while (dr.Read());\n  }\n}\n</code></pre>\n'}, {'answer_id': 12288220, 'author': 'kril', 'author_id': 1650003, 'author_profile': 'https://Stackoverflow.com/users/1650003', 'pm_score': 1, 'selected': False, 'text': '<p>I guess, you can try entity framework.</p>\n\n<pre><code>using (SchoolDBEntities ctx = new SchoolDBEntities())\n{\n     IList&lt;Course&gt; courseList = ctx.GetCoursesByStudentId(1).ToList&lt;Course&gt;();\n     //do something with courselist here\n}\n</code></pre>\n'}, {'answer_id': 56179247, 'author': 'Josué Martínez', 'author_id': 11507342, 'author_profile': 'https://Stackoverflow.com/users/11507342', 'pm_score': 0, 'selected': False, 'text': '<p>Charge the libraries</p>\n\n<pre><code>using MySql.Data.MySqlClient;\n</code></pre>\n\n<p>This is the connection:</p>\n\n<pre class="lang-cs prettyprint-override"><code>public static MySqlConnection obtenerconexion()\n{\n    string server = "Server";\n    string database = "Name_Database";\n    string Uid = "User";\n    string pwd = "Password";\n    MySqlConnection conect = new MySqlConnection("server = " + server + ";" + "database =" + database + ";" + "Uid =" + Uid + ";" + "pwd=" + pwd + ";");\n\n    try\n    {\n        conect.Open();\n        return conect;\n    }\n    catch (Exception)\n    {\n        MessageBox.Show("Error. Ask the administrator", "An error has occurred while trying to connect to the system", MessageBoxButtons.OK, MessageBoxIcon.Error);\n        return conect;\n    }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/930', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/245/']