Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Load the records from the Horses database table into an in-memory List<>
- private void LoadData()
- {
- const string connectionString = @"Provider=sqloledb; Data Source=(local)\SQLExpress; Integrated Security=SSPI; Integrated Security=SSPI; Initial Catalog=Horses";
- // this method uses the OleDb libraries to connect to a server;
- // there are other ways to handle database connectivity; this was
- // among the first for .NET applications.
- // The general steps are as follows:
- // 1. Create and open a database Connection
- // 2. Create and configure a Command for that connection
- // 3. Use a DataAdapter to execute the command and fill a DataSet
- // 4. Loop through the records of the table in the populated dataset
- // to "convert" each data record into a Horse object
- // prepare for the final step by creating an initial empty list of horses
- _horseRecords = new List<HorseRecord>();
- // Now Step 1 - We'll create the connection within a 'using' block. When the block completes,
- // the connection will automatically be disposed gracefully this way;
- using (var connection = new OleDbConnection(connectionString))
- {
- connection.Open();
- // Step 2 - create a Command object for executing a query against the database
- using (var command = connection.CreateCommand())
- {
- command.CommandType = CommandType.Text; // indicates SQL text
- command.CommandText = "SELECT name, finish, start FROM Horses";
- // Step 3 - use a DataAdapter to execute the command and fill a DataSet
- var dataset = new DataSet();
- var dataAdapter = new OleDbDataAdapter(command);
- dataAdapter.Fill(dataset);
- // Step 4 - loop through the records of the table in the populated dataset
- // to convert each data record into a Horse object
- for (var i = 0; i < dataset.Tables[0].Rows.Count; i++)
- {
- var row = dataset.Tables[0].Rows[i];
- var horse = new HorseRecord();
- horse.Name = row["name"].ToString();
- horse.Finish = Convert.ToInt32(row["finish"]);
- horse.Start = Convert.ToInt32(row["start"]);
- // add the horse to our in-memory List<>
- _horseRecords.Add(horse);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement