dir.by  
Поиск >>

Компьютер, программы
→
ADO.NET (working with the database on C#)
 Add data (insert into) to the Database using SqlCommand | ADO.NET, C# 
посмотрели 8689 раз
обновлено: 22 July 2025
The SqlCommand class with the SQL query Insert into adds data to the Database.
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();

                    // добавляем данные
                    string SQLQuery = "INSERT INTO Books (Id, Name, Price) VALUES (@Id, @Name, @Price)";
                    using (SqlCommand cmd = new SqlCommand(SQLQuery, connection))
                    {
                         // заполняем значения
                         cmd.Parameters.AddWithValue("@Id", 10);
                         cmd.Parameters.AddWithValue("@Name", "aaaa");
                         cmd.Parameters.AddWithValue("@Price", 30);
                         // выполняем запрос
                         cmd.ExecuteNonQuery();
                    }


                    // получаем данные из таблицы
                    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
 
← Previous topic
Get a scalar (single) value: Count, Min, Max, Sum, etc. | ADO.NET, C#
 
Next topic →
Change the data (update) in the Database using SqlCommand | ADO.NET, C#
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

Новость "Черная пятница" на технику Dreame в Беларуси с 17 по 30 ноября 2026 года – две недели скидок до 3400 рублей
 
• 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