# Just how do I connect to a database and also loop over a recordset in C#?

What's the most basic means to connect and also quiz a database for a set of documents in C#?

0
2019-05-03 17:58:41
Source Share

This is a different means (DataReader is much faster than this set):

string s = "";
SqlConnection conn = new SqlConnection("Server=192.168.1.1;Database=master;Connect Timeout=30;User ID=foobar;Password=raboof;");
SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 5 name, dbid FROM sysdatabases", conn);
DataTable dt = new DataTable();

da.Fill(dt);

for (int i = 0; i < dt.Rows.Count; i++)
{
s += dt.Rows[i]["name"].ToString() + " -- " + dt.Rows[i]["dbid"].ToString() + "\n";
}

MessageBox.Show(s);

0
2019-05-12 10:50:09
Source

That's most definitely an excellent way to do it. Yet you if you take place to be making use of a database that sustains LINQ to SQL, it can be a whole lot extra enjoyable. It can look something similar to this :

MyDB db = new MyDB("Data Source=...");
var q = from db.MyTable
select c;
foreach (var c in q)
Console.WriteLine(c.MyField.ToString());

0
2019-05-08 21:39:40
Source

@Goyuix-- that's superb for something created from memory. examined it below-- located the connection had not been opened up. Or else really wonderful.

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

{
{
Console.WriteLine(dr["columnName"]);
}
}
}
}

0
2019-05-07 16:47:18
Source

Very about and also from memory given that I do not have code on this laptop computer :

using (OleDBConnection conn = new OleDbConnection())
{
conn.ConnectionString = "Whatever connection string";

using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandText = "Select * from CoolTable";