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

前端 未结 8 2190
孤独总比滥情好
孤独总比滥情好 2021-01-03 17:44

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

8条回答
  •  粉色の甜心
    2021-01-03 18:14

    @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"]);
                }
            }
        }
    }
    

提交回复
热议问题