Как подключиться к базе данных c

от admin

Подключение к базе данных

Первое, что нужно сделать при работе с поставщиком данных — это установить сеанс с источником данных с помощью объекта подключения (порожденного, как вы помните, от DbConnection). У объектов подключения .NET имеется форматированная строка подключения, которая содержит ряд пар имя/значение, разделенных точками с запятой. Эта информация содержит имя машины, к которой нужно подключиться, необходимые параметры безопасности, имя базы данных на этой машине и другую информацию, зависящую от поставщика.

В следующем коде иллюстрируется создание, открытие и закрытие соединения с базой данных SqlServer:

Из приведенного выше кода можно понять, что имя Initial Catalog относится к базе данных, с которой нужно установить сеанс. Имя Data Source определяет имя машины, на которой расположена база данных. Элемент (local) позволяет указать текущую локальную машину (независимо от конкретного имени этой машины), а элемент \SQLEXPRESS сообщает поставщику SQL Server, что вы подключаетесь к стандартной инсталляции SQL Server Express (если вы создали AutoLot с помощью полной версии SQL Server 2005 или более ранней, укажите Data Source=(local)). В данном примере я использовал вместо (local) полное название имени компьютера (MICROSOF-1EA29E), на котором развернута версия SQL Server.

Кроме того, можно указать любое количество элементов, которые задают полномочия безопасности. В нашем примере имени Integrated Security присвоено значение SSPI (что эквивалентно true), которое использует для аутентификации пользователя текущие полномочия учетной записи Windows.

Назначение каждой пары имя/значение для вашей СУБД можно узнать в документации по NET Framework 4.0 SDK, в описании свойства ConnectionString объекта подключения для вашего поставщика данных.

При наличии строки подключения вызов Open() устанавливает соединение с СУБД. В дополнение к членам ConnectionString, Open() и Close() объект подключения содержит ряд членов, которые позволяют настроить дополнительные параметры подключения, например, время тайм-аута и информацию, относящуюся к транзакциям.

Ниже приведены некоторые члены базового класса DbConnection:

BeginTransaction()

Используется для начала транзакции базы данных

ChangeDatabase()

Изменяет базу данных для открытого подключения

ConnectionTimeout

Свойство только для чтения. Возвращает время ожидания при установке подключения, после которого ожидание прекращается и выдается сообщение об ошибке (по умолчанию 15 секунд). Для изменения этого времени нужно изменить в строке подключения сегмент Connect Timeout (например, Connect Timeout=30)

Database

Свойство только для чтения. Содержит имя базы данных, с которой связан объект подключения

DataSource

Свойство только для чтения. Содержит местоположение базы данных, с которой связан объект подключения

GetSchema()

Этот метод возвращает объект DataTable, содержащий информацию схемы из источника данных

State

Свойство только для чтения. Содержит текущее состояние подключения в виде одного из значений перечисления ConnectionState

Свойства типа DbConnection предназначены в основном только для чтения и поэтому нужны, если требуется получить характеристики подключения во время выполнения. Если понадобится изменить стандартные значения, необходимо будет изменить саму строку подключения. Например, можно изменить время тайм-аута с 15 на 30 секунд:

Программная работа со строками подключения может оказаться несколько затруднительной, поскольку они часто представлены в виде строковых литералов, которые трудно обрабатывать и контролировать на наличие ошибок. Поставщики данных ADO.NET, разработанные Microsoft, поддерживают объекты построителей строк подключения (connection string builder object) (аналог StringBuilder), которые позволяют устанавливать пары имя/значение с помощью строго типизированных свойств. Рассмотрим следующую модификацию нашего метода Main():

В этом варианте создается экземпляр SqlConnectionStringBuilder, устанавливаются его свойства, и выбирается внутренняя строка из свойства ConnectionString. Здесь использован стандартный конструктор типа. При этом можно также создать экземпляр объекта построителя для строки подключения поставщика данных, передав в качестве отправной точки существующую строку подключения (это может оказаться удобным при динамическом чтении значений из файла App.config).

Эффективное использование соединений

В общем случае при использовании в .NET таких скудных ресурсов, как соединения с базой данных, окна или графические объекты, хорошим тоном является закрытие ресурса после работы с ним. Хотя проектировщики .NET реализовали автоматическую сборку мусора, которая рано или поздно произойдет, необходимо освобождать ресурсы как можно раньше, чтобы избежать дефицита ресурсов.

Это также касается и написания кода, обращающегося к базе данных, потому что сохранение подключений открытыми дольше, чем нужно, может повлиять на другие сеансы.

В крайних случаях незакрытое соединение может полностью блокировать доступ других пользователей к целым множествам таблиц, нанося огромный ущерб производительности приложения. Закрытие соединений базы данных должно считаться обязательным, поэтому в настоящем разделе мы продемонстрируем структуру кода, которая минимизирует риск оставления ресурсов в открытом состоянии.

Вариант обеспечения очистки ресурсов состоит в применении блоков try. catch. finally, и он гарантирует закрытие любых открытых соединений внутри блока finally. Рассмотрим краткий пример:

C# Database Connection: How to connect SQL Server (Example)

It can work with different types of databases. It can work with the most common databases such as Oracle and Microsoft SQL Server.

It also can work with new forms of databases such as MongoDB and MySQL.

In this C# sql connection tutorial, you will learn-

Fundamentals of Database connectivity

C# and .Net can work with a majority of databases, the most common being Oracle and Microsoft SQL Server. But with every database, the logic behind working with all of them is mostly the same.

In our examples, we will look at working the Microsoft SQL Server as our database. For learning purposes, one can download and use the Microsoft SQL Server Express Edition, which is a free database software provided by Microsoft.

  1. Connection – To work with the data in a database, the first obvious step is the connection. The connection to a database normally consists of the below-mentioned parameters.
    1. Database name or Data Source – The first important parameter is the database name to which the connection needs to be established. Each connection can only work with one database at a time.
    2. Credentials – The next important aspect is the username and password which needs to be used to establish a connection to the database. It ensures that the username and password have the necessary privileges to connect to the database.
    3. Optional parameters – For each database type, you can specify optional parameters to provide more information on how .net should handle the connection to the database. For example, one can specify a parameter for how long the connection should stay active. If no operation is performed for a specific period of time, then the parameter would determine if the connection has to be closed.

    Ok, now that we have seen the theory of each operation, let’s jump into the further sections to look at how we can perform database operations in C#.

    SQL Command in c#

    SqlCommand in C# allow the user to query and send the commands to the database. SQL command is specified by the SQL connection object. Two methods are used, ExecuteReader method for results of query and ExecuteNonQuery for insert, Update, and delete commands. It is the method that is best for the different commands.

    How to connect C# to Database

    Let’s now look at the code, which needs to be kept in place to create a connection to a database. In our example, we will connect to a database which has the name of Demodb. The credentials used to connect to the database are given below

    • Username – sa
    • Password – demo123

    We will see a simple Windows forms application to work with databases. We will have a simple button called “Connect” which will be used to connect to the database.

    So let’s follow the below steps to achieve this

    Step 1) The first step involves the creation of a new project in Visual Studio. After launching Visual Studio, you need to choose the menu option New->Project.

    C# Access Database

    Step 2) The next step is to choose the project type as a Windows Forms application. Here, we also need to mention the name and location of our project.

    C# Access Database

    1. In the project dialog box, we can see various options for creating different types of projects in Visual Studio. Click the Windows option on the left-hand side.
    2. When we click the Windows options in the previous step, we will be able to see an option for Windows Forms Application. Click this option.
    3. We then give a name for the application which in our case is “DemoApplication”. We also need to provide a location to store our application.
    4. Finally, we click the ‘OK’ button to let Visual Studio to create our project.

    C# Access Database

    Step 4) Now double click the form so that an event handler is added to the code for the button click event. In the event handler, add the below code.

    C# Access Database

    Code Explanation:-

    1. The first step is to create variables, which will be used to create the connection string and the connection to the SQL Server database.
    2. The next step is to create the connection string. The connecting string needs to be specified correctly for C# to understand the connection string. The connection string consists of the following parts
      1. Data Source – This is the name of the server on which the database resides. In our case, it resides on a machine called WIN- 50GP30FGO75.
      2. The Initial Catalog is used to specify the name of the database
      3. The UserID and Password are the credentials required to connect to the database.

      When the above code is set, and the project is executed using Visual Studio, you will get the below output. Once the form is displayed, click the Connect button.

      C# Access Database

      When you click on “connect” button, from the output, you can see that the database connection was established. Hence, the message box was displayed.

      Access data with the SqlDataReader

      To showcase how data can be accessed using C#, let us assume that we have the following artifacts in our database.

      1. A table called demotb. This table will be used to store the ID and names of various Tutorials.
      2. The table will have 2 columns, one called “TutorialID” and the other called “TutorialName.”
      3. For the moment, the table will have 2 rows as shown below.

      Let’s change the code in our form, so that we can query for this data and display the information via a Messagebox. Note that all the code entered below is a continuation of the code written for the data connection in the previous section.

      Step 1) Let’s split the code into 2 parts so that it will be easy to understand for the user.

      • The first will be to construct our “select” statement, which will be used to read the data from the database.
      • We will then execute the “select” statement against the database and fetch all the table rows accordingly.

      C# Access Database

      Code Explanation:-

      1. The first step is to create the following variables
        1. SQLCommand – The ‘SQLCommand’ is a class defined within C#. This class is used to perform operations of reading and writing into the database. Hence, the first step is to make sure that we create a variable type of this class. This variable will then be used in subsequent steps of reading data from our database.
        2. The DataReader object is used to get all the data specified by the SQL query. We can then read all the table rows one by one using the data reader.
        3. We then define 2 string variables, one is “SQL” to hold our SQL command string. The next is the “Output” which will contain all the table values.

        Step 2) In the final step, we will just display the output to the user and close all the objects related to the database operation.

        C# Access Database

        Code Explanation:-

        1. We will continue our code by displaying the value of the Output variable using the MessageBox. The Output variable will contain all the values from the demotb table.
        2. We finally close all the objects related to our database operation. Remember this is always a good practice.

        When the above code is set, and the project is run using Visual Studio, you will get the below output. Once the form is displayed, click the Connect button.

        Output:-

        C# Access Database

        From the output, you can clearly see that the program was able to get the values from the database. The data is then displayed in the message box.

        C# Insert Into Database

        Just like Accessing data, C# has the ability to insert records into the database as well. To showcase how to insert records into our database, let’s take the same table structure which was used above.

        TutorialID TutorialName
        1 C#
        2 ASP.Net

        Let’s change the code in our form, so that we can insert the following row into the table

        TutorialID TutorialName
        3 VB.Net

        So let’s add the following code to our program. The below code snippet will be used to insert an existing record in our database.

        C# Access Database

        Code Explanation:-

        1. The first step is to create the following variables
          1. SQLCommand – This data type is used to define objects which are used to perform SQL operations against a database. This object will hold the SQL command which will run against our SQL Server database.
          2. The DataAdapter object is used to perform specific SQL operations such as insert, delete and update commands.
          3. We then define a string variable, which is “SQL” to hold our SQL command string.

          When the above code is set, and the project is executed using Visual Studio, you will get the below output. Once the form is displayed, click the Connect button.

          Output:-

          C# Access Database

          If you go to SQL Server Express and see the rows in the demotb table, you will see the row inserted as shown below

          C# Access Database

          C# Update Database

          Just like Accessing data, C# has the ability to update existing records from the database as well. To showcase how to update records into our database, let’s take the same table structure which was used above.

          TutorialID TutorialName
          1 C#
          2 ASP.Net
          3 VB.Net

          Let’s change the code in our form, so that we can update the following row. The old row value is TutorialID as “3” and Tutorial Name as “VB.Net”. Which we will update it to “VB.Net complete” while the row value for Tutorial ID will remain same.

          Old row

          TutorialID TutorialName
          3 VB.Net

          New row

          TutorialID TutorialName
          3 VB.Net complete

          So let’s add the following code to our program. The below code snippet will be used to update an existing record in our database.

          C# Access Database

          C# SqlCommand Example With Code Explanation:-

          1. The first step is to create the following variables
            1. SQLCommand – This data type is used to define objects which are used to perform SQL operations against a database. This object will hold the SQL command which will run against our SQL Server database.
            2. The dataadapter object is used to perform specific SQL operations such as insert, delete and update commands.
            3. We then define a string variable, which is SQL to hold our SQL command string.

            When the above code is set, and the project is executed using Visual Studio, you will get the below output. Once the form is displayed, click the Connect button.

            Output:-

            C# Access Database

            If you actually go to SQL Server Express and see the rows in the demotb table, you will see the row was successfully updated as shown below.

            C# Access Database

            Deleting Records

            Just like Accessing data, C# has the ability to delete existing records from the database as well. To showcase how to delete records into our database, let’s take the same table structure which was used above.

            TutorialID TutorialName
            1 C#
            2 ASP.Net
            3 VB.Net complete

            Let’s change the code in our form, so that we can delete the following row

            TutorialID TutorialName
            3 VB.Net complete

            So let’s add the following code to our program. The below code snippet will be used to delete an existing record in our database.

            C# Access Database

            Code Explanation:-

            1. The Key difference in this code is that we are now issuing the delete SQL statement. The delete statement is used to delete the row in the demotb table in which the TutorialID has a value of 3.
            2. In our data adapter command, we now associate the insert SQL command to our adapter. We also then issue the ExecuteNonQuery method which is used to execute the Delete statement against our database.

            When the above code is set, and the project is executed using Visual Studio, you will get the below output. Once the form is displayed, click the Connect button.

            Output:-

            C# Access Database

            If you actually go to SQL Server Express and see the rows in the demotb table, you will see the row was successfully deleted as shown below.

            C# Access Database

            Connecting Controls to Data

            In the earlier sections, we have seen how to we can use C# commands such as SQLCommand and SQLReader to fetch data from a database. We also saw how we read each row of the table and use a messagebox to display the contents of a table to the user.

            But obviously, users don’t want to see data sent via message boxes and would want better controls to display the data. Let’s take the below data structure in a table

            TutorialID TutorialName
            1 C#
            2 ASP.Net
            3 VB.Net complete

            From the above data structure, the user would ideally want to see the TutorialID and Tutorial Name displayed in a textbox. Secondly, they might want to have some sort of button control which could allow them to go to the next record or to the previous record in the table. This would require a bit of extra coding from the developer’s end.

            The good news is that C# can reduce the additional coding effort by allowing binding of controls to data. What this means is that C# can automatically populate the value of the textbox as per a particular field of the table.

            So, you can have 2 textboxes in a windows form. You can then link one text box to the TutorialID field and another textbox to the TutorialName field. This linking is done in the Visual Studio designer itself, and you don’t need to write extra code for this.

            Visual Studio will ensure that it writes the code for you to ensure the linkage works. Then when you run your application, the textbox controls will automatically connect to the database, fetch the data and display it in the textbox controls. No coding is required from the developer’s end to achieve this.

            Let’s look at a code example of how we can achieve binding of controls.

            In our example, we are going to create 2 textboxes on the windows form. They are going to represent the Tutorial ID and Tutorial Name respectively. They will be bound to the Tutorial ID and TutorialName fields of the database accordingly.

            Let’s follow the below-mentioned steps to achieve this.

            Step 1) Construct the basic form. In the form drag and drop 2 components- labels and textboxes. Then carry out the following substeps

            1. Put the text value of the first label as TutorialID
            2. Put the text value of the second label as TutorialName
            3. Put the name property of the first textbox as txtID
            4. Put the name property of the second textbox as txtName

            Below is the how the form would look like once the above-mentioned steps are performed.

            C# Access Database

            Step 2) The next step is to add a binding Navigator to the form. The binding Navigator control can automatically navigate through each row of the table. To add the binding navigator, just go to the toolbox and drag it to the form.

            C# Access Database

            Step 3) The next step is to add a binding to our database. This can be done by going to any of the Textbox control and clicking on the DataBindings->Text property. The Binding Navigator is used to establish a link from your application to a database.

            When you perform this step, Visual Studio will automatically add the required code to the application to make sure the application is linked to the database. Normally the database in Visual Studio is referred to as a Project Data Source. So to ensure the connection is established between the application and the database, the first step is to create a project data source.

            The following screen will show up. Click on the link- “Add Project Data Source”. When you click on the project data source, you will be presented with a wizard; this will allow you to define the database connection.

            C# Access Database

            Step 4) Once you click on the Add Project Data Source link, you will be presented with a wizard which will be used to create a connection to the demotb database. The following steps show in detail what needs to be configured during each step of the wizard.

            1. In the screen which pops up , choose the Data Source type as Database and then click on next button.

            C# Access Database

            1. In the next screen, you need to start the creation of the connection string to the database. The connection string is required for the application to establish a connection to the database. It contains the parameters such as server name, database name, and the name of the driver.
              1. Click on the New connection button
              2. Choose the Data Source as Microsoft SQL Server
              3. Click the Continue button.

              C# Access Database

              1. Next, you need to add the credentials to connect to the database
                1. Choose the server name on which the SQL Server resides
                2. Enter the user id and password to connect to the database
                3. Choose the database as demotb
                4. Click the ‘ok’ button.

                C# Access Database

                1. In this screen, we will confirm all the settings which were carried on the previous screens.
                  1. Choose the option “Yes” to include sensitive data in the connection string
                  2. Click on the “Next” button.

                  C# Access Database

                  1. In the next screen, click on the “Next” button to confirm the creation of the connection string

                  C# Access Database

                  1. In this step,
                  1. Choose the tables of Demotb, which will be shown in the next screen.
                  2. This table will now become an available data source in the C# project

                  C# Access Database

                  When you click the Finish button, Visual Studio will now ensure that the application can query all the rows in the table Demotb.

                  Step 5) Now that the data source is defined, we now need to connect the TutorialID and TutorialName textbox to the demotb table. When you click on the Text property of either the TutorialID or TutorialName textbox, you will now see that the binding source to Demotb is available.

                  For the first text box choose the Tutorial ID. Repeat this step for the second textbox and choose the field as TutorialName. The below steps shows how we can navigate to each control and change the binding accordingly.

                  1. Click on the Tutorial ID control.

                  C# Access Database

                  1. In the Properties window, you will see the properties of the TutorialID textbox. Go to the text property and click on the down arrow button.

                  C# Access Database

                  1. When you click the down arrow button, you will see the demotbBinding Source option. And under this, you will see the options of TutorialName and TutorialID. Choose the Tutorial ID one.

                  C# Access Database

                  Repeat the above 3 steps for the Tutorial Name text box.

                  1. So click on the Tutorial Name text box
                  2. Go to the properties window
                  3. Choose the Text property
                  4. Choose the TutorialName option under demotbBindingSource

                  Step 6) Next we need to change the Binding Source property of the BindingNavigator to point to our Demotb data source. The reason we do this is that the Binding Navigator also needs to know which table it needs to refer to.

                  The Binding Navigator is used to select the next or previous record in the table. So even though the data source is added to the project as a whole and to the text box control, we still need to ensure the Binding Navigator also has a link to our data source. In order to do this, we need to click the Binding navigator object, go to the Binding Source property and choose the one that is available

                  C# Access Database

                  Next, we need to go to the Properties window so that we can make the change to Binding Source property.

                  C# Access Database

                  When all of the above steps are executed successfully, you will get the below-mentioned output.

                  Output:-

                  C# Access Database

                  Now when the project is launched, you can see that the textboxes automatically get the values from the table.

                  C# Access Database

                  When you click the Next button on the Navigator, it automatically goes to the next record in the table. And the values of the next record automatically come in the text boxes

                  C# DataGridView

                  Data Grids are used to display data from a table in a grid-like format. When a user sees’s table data, they normally prefer seeing all the table rows in one shot. This can be achieved if we can display the data in a grid on the form.

                  C# and Visual Studio have inbuilt data grids, this can be used to display data. Let’s take a look at an example of this. In our example, we will have a data grid, which will be used to display the Tutorial ID and Tutorial Name values from the demotb table.

                  Step 1) Drag the DataGridView control from the toolbox to the Form in Visual Studio. The DataGridView control is used in Visual Studio to display the rows of a table in a grid-like format.

                  C# Access Database

                  Step 2) In the next step, we need to connect our data grid to the database. In the last section, we had created a project data source. Let’s use the same data source in our example.

                  1. First, you need to choose the grid and click on the arrow in the grid. This will bring up the grid configuration options.
                  2. In the configuration options, just choose the data source as demotbBindingSource which was the data source created in the earlier section.

                  C# Access Database

                  If all the above steps are executed as shown, you will get the below-mentioned output.

                  Output:-

                  C# Access Database

                  From the output, you can see that the grid was populated by the values from the database.

                  Как подключиться к базе данных c

                  Данное руководство устарело. Актуальное руководство: Руководство по ASP.NET Core

                  Чтобы хранить данные, нам естественным образом нужна база данных. Как правило, в качестве базы данных используется MS SQL Server, на примере которого мы и посмотрим весь процесс создания БД и подключения к ней.

                  Мы можем создать базу данных прямо в проекте, либо же создать ее на сервере MS SQL. Для хранения баз данных проекте у нас предназначена папка App_Data. Для этого нажмем правой кнопкой мыши на папку App_Data и в появившемся контекстном меню выберем Add-> New Item. . В появившемся окне добавления нового элемента выберем SQL Server Database и назовем новую базу данных Bookstore.mdf:

                  Мы можем создать базу данных равнозначным образом и на сервере. После этого база данных добавляется в проект, и мы можем увидеть ее в папке App_Data. Теперь в обозревателе баз данных (окно Database Explorer ) мы можем подключиться к ней и создать таблицы, которые будут хранить данные.

                  Раскроем узел Bookstore.mdf и найдем узел Tables. Нажмем на этот узел правой кнопкой мыши и в появившемся меню выберем пункт Add New Table . И перед нами появится окно, в котором нам надо определить названия и типы столбцов новой таблицы. По соглашениям о наименованиях таблицы при работе с Entity Framework должны соответствовать имени модели. То есть, так как наша модель называется Book , то таблица будет называться Books . А Entity Framework автоматически распознает, что таблица Books соответствует классу Book .

                  Итак, создадим структуру таблицы:

                  Не забудьте установить ниже в окне Properties (в Visual Stidio 2010 — окно Column Properties) для столбца Id соответствующие параметры для первичного ключа:

                  После этого, если мы работаем с Visual Studio 2010, нам будет предложено просто ввести имя таблицы — введем имя Books, и затем таблица добавляется в БД.

                  А в Visual Studio Express 2012 for Web нам надо сгенерировать таблицу на основе заданного выше определения. Для этого нажмем на кнопку Update:

                  В появившемся диалоговом окне нажмем на кнопку Update Database. После этого в нашу базу данных добавляется только что сгенерированная таблица. Подобным образом определим таблицу Purchases для модели Purchase:

                  Добавим в таблицу Books несколько записей:

                  Теперь, во-первых, чтобы взаимодействовать с БД, нам нужен класс контекста данных, пусть это будет следующий класс BookContext:

                  Во-вторых, определим строку подключения к БД. Для этого откроем файл Web.config и добавим в конец секции configuration определение строки подключения. Однако тут надо сразу заметить, что для Visual Studio 2010 строка подключения будет отличаться от строки подключения, которая используется в Visual Studio 2012.

                  Итак, строка подключения для Visual Studio 2010 будет выглядеть так:

                  Для Visual Studio 2012 будет выглядеть определение строки подключения будет выглядеть следующим образом:

                  В Visual Studio 2012 в отличие от 2010-й версии мы можем использовать режим LocalDB, который предназначен прежде всего для разработчиков, представляя некоторую упрощенную версию. Поэтому в данном случае в качестве источника данных используется (LocalDB)\v11.0.

                  Обратите внимание, что в обоих случаях свойство name=»BookContext» должно содержать название контекста данных.

                  Использование подстановки |DataDirectory| позволяет опустить полный физический путь к базе данных, которая хранится в папке App_Data.

                  Теперь мы можем получить содержимое таблицы Books в контроллере Home:

                  И вывести данные в представлении Index.cshtml:

                  Закрытие подключения

                  Чтобы наверняка быть уверенным, что подключение к базе данных закрыто, следует вызывать метод Dispose у контекста данных:

                  Как подключиться к MySQL используя ADO.NET

                  Когда я начал свое знакомство с технологией ADO.NET меня сразу заинтересовал вопрос: «Как можно подключиться к MySQL, используя технологию ADO.NET». Я начал искать решения. Сейчас, когда я реализовал у себя на компьютере все это, хочу с вами поделиться своим опытом и навыками. Давайте для начала разберем, что нам понадобится для реализации этой затеи.

                  1. Сервер баз данных MySQL
                  2. Visual Studio (В моем примере это Visual Studio 2010)
                  3. Библиотека для работы с MySQL

                  Надеюсь, что у вас уже установлен сервер баз данных MySQL и программа Visual Studio. Если нет, тогда сделайте установку до того, как приступите к работе. Все готово. Visual Studio установлена, сервер баз данных MySQL установлен. Первым делом нам понадобится dll библиотека MySQL, которая будет помогать работать с ADO.NET в среде .NET Framework. Скачать библиотеку можно на официальном сайте MySQL по адресу: dev.mysql.com.

                  Для скачивания на сайте доступны два варианта: первый — установщик, второй — архив, в примере будет рассматриваться первый вариант. И так, Скачали? Установили? Прекрасно, идем дальше, дальше нам нужно обратиться к папке, в которую мы установили dll библиотеку MySQL, у меня путь к библиотеке выглядит так — C:\Program Files\MySQL\MySQL Connector Net 6.4.4\Assemblies\v2.0 в этой папке находим и копируем файл MySql.Date.dll в буфер.

                  Создаем консольное приложение в Visual Studio через Файл -> Создать -> Проект (File -> New -> Project) или Ctrl + Shift + N. Выбираем язык Visual C# консольное приложение нажимает ОК. Обращаемся к папке проекта где лежать все файлы, только что созданного консольного приложения <название проекта>/bin/Debug/ копируем суда файл MySql.Date.dll. В обозревателе решения(solution Explorer) в меню «Ссылки(references)» необходимо «Добавить ссылку(add a link)».

                  В результате в обозревателе решения(solution Explorer) в меню «Ссылки(references)» появиться ссылка на dll библиотеку MySql.Data. Очень хорошо, теперь остается подключить эту самую библиотеку в наш проект это делается очень просто:

                  Половину работы мы уже сделали, остается написать программный код, который будет делать соединение с базой MySQL и выполнять запросы. Первое, что нам понадобиться — настройки соединения с базой данных:

                  Объект MySqlConnection — соединение с базой данных. Следующим шагом мы создаем объект MySqlCommand с именем mysql_query используя текущее подключение создаем SQL запрос, который будет храниться в mysql_query. Объект MySqlCommand — выполняет SQL команд.

                  Дальше для подключение и соединения с базой данных нужно вызвать метод .Open():

                  Теперь, чтобы увидеть обработанный запрос нужно создать объект MySqlDataReader:

                  Для выполнения SQL запроса на консольное окно нам понадобится метод ExecuteReader(), Read(), GetString() и цикл while. Метод ExecuteReader() выполняет запрос и возвращает 0 и более строк результата. Метод Read() — переходит от одной строки к другой пока конец данных не будет достигнут. Метод GetString() извлекает конкретное значение, которое нужно вернуть.

                  В конце, когда выполнился запрос, обязательно нужно закрыть соединение с базой данных используя метод .Close():

                  В результате нам программа должна показать список пользователей, которые существуют в базе данных. В моем случае это один пользователь root у вас может быть их несколько. Для закрепления данной темы давайте реализуем функционал, который будет выводить нам небольшую информацию о пользователе, а именно — имя пользователя, пароль пользователя и имя локального подключения. Полный код программы и ссылку где можно скачать проект представлен ниже.

                  Читать:
                  От чего может сгореть материнская плата

Похожие статьи