dir.by  
Programming, development, testing
ADO.NET (working with the database on C#)
Read the data (select) from the Database using SqlCommand and SqlDataReader in ADO.NET C#. Database Type Mapping
  Looked at 7434 times    
 Read the data (select) from the Database using SqlCommand and SqlDataReader in ADO.NET C#. Database Type Mapping 
last updated: 22 July 2025
The SqlCommand class with the SQL query Select reads the data from Database and puts it in SqlDataReader.
Step 1. Creating a new application
Step 2. Let's write the code
  C#     В файле Program.cs напишем код:
using System;

// подключаем SQL ADO.NET
using Microsoft.Data.SqlClient;

namespace ConsoleApplication1
{
     class Program
     {
          static void Main(string[] args)
          {
               // connection string
               string connectionString = @"Data Source=EVGENI;Initial Catalog=MyDatabase1;Integrated Security=True";

               // connect to db
               using (SqlConnection connection = new SqlConnection(connectionString))
               {
                    // open db
                    connection.Open();

                    // получаем данные из таблицы
                    using (SqlCommand command = new SqlCommand("SELECT Id, Name, Price FROM Books", connection))
                    {
                         SqlDataReader reader = command.ExecuteReader();
                         // есть ли данные
                         if (reader.HasRows)
                         {
                              // построчно считываем данные
                              while (reader.Read())
                              {
                                   int id = reader.GetInt32(0); // Id
                                   string name = reader.GetString(1); // Name
                                   int price = reader.GetInt32(2); // Price
                                   // object price = reader.GetValue(2); // получаем результат как object

                                   // выводим на экран
                                   Console.WriteLine("Id={0}, Name={1}, Price={2}", id, name, price);
                              }
                         }
                    }
               }
          }
     }
}
Example result
Mapping Database Types in SqlDataReader
In our example, we use the GetInt32() and GetString() methods of the SqlDataReader class to retrieve the data
  C#  
SqlDataReader reader = command.ExecuteReader();
...
int id = reader.GetInt32(0); // Id
string name = reader.GetString(1); // Name
int price = reader.GetInt32(2); // Price
To obtain data of other types, there are methods:
Type in SQL
Type in .NET
bigint
Int64 reader.GetInt64(...)
binary
Byte[] reader.GetBytes(...)
bit
Boolean reader.GetBoolean(...)
char[]
String reader.GetString(...)
char[]
Char[] reader.GetChars(...)
datetime
DateTime reader.GetDateTime(...)
decimal
Decimal reader.GetDecimal(...)
float
Double reader.GetDouble(...)
image
Byte[] reader.GetBytes(...)
long varbinary
Byte[] reader.GetStream(...)
int
Int32 reader.GetInt32(...)
Int32 the same as int
money
Decimal reader.GetDecimal(...)
nchar[]
String reader.GetString(...)
nchar[]
Char[] reader.GetChars(...)
ntext
String reader.GetString(...)
ntext
Char[] reader.GetChars(...)
numeric
Decimal reader.GetDecimal(...)
nvarchar
String reader.GetString(...)
nvarchar
Char[] reader.GetChars(...)
real
Single reader.GetFloat(...)
Single the same as float
smalldatetime
DateTime reader.GetDateTime(...)
smallint
Intl6 reader.GetIntl6(...)
smallmoney
Decimal reader.GetDecimal(...)
sql variant
Object reader.GetValue(...)
long varchar
String reader.GetString(...)
long varchar
Char[] reader.GetChars(...)
timestamp
Byte[] reader.GetBytes(...)
tinyint
Byte reader.GetByte(...)
uniqueidentifier
Guid reader.GetGuid(...)
varbinary
Byte[] reader.GetBytes(...)
varchar
String reader.GetString(...)
varchar
Char[] reader.GetChars(...)
 
← Previous topic
Let's create a ADO.NET console application (C#, database)
 
Next topic →
Read (select) data from the Database using SqlDataAdapter and DataSet | ADO.NET, C#
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

Экскурсии по Москве Экскурсии по Москве: пешеходные, автобусные и речные прогулки на любой вкус
  Объявления  
  Объявления  
 
What is ADO.NET?
Let's create a ADO.NET console application (C#, database)
Working with data in ADO.NET
Read the data (select) from the Database using SqlCommand and SqlDataReader in ADO.NET C#. Database Type Mapping
Read (select) data from the Database using SqlDataAdapter and DataSet | ADO.NET, C#
Get a scalar (single) value: Count, Min, Max, Sum, etc. | ADO.NET, C#
Add data (insert into) to the Database using SqlCommand | ADO.NET, C#
Change the data (update) in the Database using SqlCommand | ADO.NET, C#
Delete data in the Database using SqlCommand | ADO.NET, C#
Stored procedures in ADO.NET
Stored procedures in ADO.NET | C#
Transactions in ADO.NET
Transactions in ADO.NET | Database in the C# console application
Reading the picture from the database ADO.NET
Read the image from the database and save it to a file | ADO.NET, C#
Additional topics, questions
Database connection string | ADO.NET, C#

  Ваши вопросы присылайте по почте: info@dir.by  
Яндекс.Метрика