Created
July 7, 2020 23:37
-
-
Save luisdeol/aaff00982a9032ab4389bf7a18d2a760 to your computer and use it in GitHub Desktop.
4.2: Connecting and Retrieving data from SQL Server.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Data.SqlClient; | |
| namespace _42_ConsumeData | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| const string connectionString = "Server=LAPTOP-201QPF8A\\SQLEXPRESS;Database=EcommerceDb;Trusted_Connection=true"; | |
| using (var sqlConnection = new SqlConnection(connectionString)) | |
| { | |
| sqlConnection.Open(); | |
| const string query = "SELECT Id, Description, Quantity, Price FROM Product"; | |
| var sqlCommand = new SqlCommand(query, sqlConnection); | |
| var sqlDataReader = sqlCommand.ExecuteReader(); | |
| while(sqlDataReader.Read()) | |
| { | |
| var id = sqlDataReader["Id"]; // sqlDataReader.GetInt32(0); | |
| var description = sqlDataReader["Description"]; // sqlDataReader.GetString(1); | |
| var quantity = sqlDataReader["Quantity"]; // sqlDataReader.GetInt32(2); | |
| var price = sqlDataReader["Price"]; // sqlDataReader.GetDecimal(3); | |
| Console.WriteLine( | |
| $"Id: {id}, " + | |
| $"Description: {description}, " + | |
| $"Quantity: {quantity}, " + | |
| $"Price: {price}"); | |
| } | |
| sqlDataReader.Close(); | |
| } | |
| Console.ReadKey(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment