How do I connect to a database and loop over a recordset in C#?
@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"]); } } }}
Very roughly and from memory since I don't have code on this laptop:
using (OleDBConnection conn = new OleDbConnection()){ conn.ConnectionString = "Whatever connection string"; using (OleDbCommand cmd = new OleDbCommand()) { cmd.Connection = conn; cmd.CommandText = "Select * from CoolTable"; using (OleDbDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { // do something like Console.WriteLine(dr["column name"] as String); } } }}
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:
MyDB db = new MyDB("Data Source=...");var q = from db.MyTable select c;foreach (var c in q) Console.WriteLine(c.MyField.ToString());