How do you connect to Sql Server at Docker on macOS?



  • Created a console project, writing Visual Studio Code using macOS, that's the connection code:

    public class ApplicationContext : DbContext
    {
        public DbSet<User> Users { get; set; }
    
    public ApplicationContext()
    {
        Database.EnsureCreated();
    }
    
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=localhost\\mssqllocaldb;Database=thevckitdb;user=sa;password=@Generally090");
    }
    

    }

    The simplest example of adding data:

    static void Main(string[] args)
    {
    try
    {
    using (ApplicationContext db = new ApplicationContext())
    {
    // создаем два объекта User
    User user1 = new User { Name = "Tom", Age = 33 };
    User user2 = new User { Name = "Alice", Age = 26 };

            // добавляем их в бд
            db.Users.Add(user1);
            db.Users.Add(user2);
            db.SaveChanges();
            Console.WriteLine("Объекты успешно сохранены");
    
            // получаем объекты из бд и выводим на консоль
            var users = db.Users.ToList();
            Console.WriteLine("Список объектов:");
            foreach (User u in users)
            {
                Console.WriteLine($"{u.Id}.{u.Name} - {u.Age}");
            }
        }
    }
    catch (System.Exception ex)
    {
        // TODO
        System.Console.WriteLine(ex.Message, ex.Source);
    }
    

    }

    In project launch, exception:

    A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 25 - Connection string is not valid)

    I remind you I work for macOS.



  • The distinguished colleagues, I think you've already given the author enough information to deal with the problem on his own.

    I apologize in advance if I repeat the advice that has already been given in the comments.

    So, we have a mission: to launch an annex written on the NET Core and working with the MS SQL database.

    I'd take this job like this:

    Step 1. Launch MS SQL.

    This is done by the team.

        sudo docker run -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=<здесь должен быть пароль SA>" -v /mssql_data:/var/opt/mssql/data -p 1433:1433  --name sql1 -h sql1 -d mcr.microsoft.com/mssql/server:2019-latest
    

    On this team. sql1 - that's the name of the container, mcr.microsoft.com/mssql/server:2019-latest is the name of the image from which MS SQL is established.

    As a result, a container with a base has to be started it can be verified by a team. sudo docker ps - There must be a container sql1.

    Step 2. We're building a database (or reconstructing it from the backup)

    Microsoft's offering a really convenient thing-- Microsoft SQL management studio-- which, for now, seems to be working just under windows :-

    Fortunately, there's a project.

    https://github.com/Microsoft/azuredatastudio

    It's the one that works under MacOS. I don't think it's very difficult to deal with the documentation that's in the repository. To be certain, we'll call a database we've created. MyDatabase

    Step 3. Let's make sure we can connect from NET Core.

    I'm offering a simple "working-crostian" method to create a simple console app.dotnet new consoleadd dependence dotnet add package System.Data.SqlClient and write a check code that opens the connection.

    As a result, I received a project (the native I called SqlTest) containing this SqlTest.csproj.

    <Project Sdk="Microsoft.NET.Sdk">
    

    <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
    </PropertyGroup>

    <ItemGroup>
    <PackageReference Include="System.Data.SqlClient" Version="4.8.3" />
    </ItemGroup>

    </Project>

    And this is the Program.cs:

        using System;
    using System.Data.SqlClient;

    namespace SqlTest
    {
        class Program {
            static void Main(string[] args) {
                const string sqlConnectionString = "Password=&lt;your password here&gt;;Persist Security Info=True;User ID=sa;Initial Catalog=MyDatabase;Data Source=localhost";
                try{
                    using( SqlConnection cn = new SqlConnection(sqlConnectionString) ){
                        cn.Open();
                        Console.WriteLine("Hey! Connection open!");
                    }
                } catch(Exception ex) {
                    Console.WriteLine($"Error: {ex.Message}");
                }
            }
        }
    }
    

    Naturally, the expression <your password here> You need to replace your password. For localhost, specific ip may be inserted (e.g. where the container is not launched on a local vehicle)

    As a result of the launch, a successful connection to the database should be removed.

    All right, we created sqlConnectionString, and we checked that the connection works with this connection.

    This line can now be transferred to any other NET Core project.

    Now let's see what steps we have taken:

    Started a container with a base, and specialised what port should be "from it to the outside" (1433, sometimes default, so SQL connection string may not be written)

    Created a database. In doing so, as long as we work on behalf of the SA user, this is not recommended for safety reasons, but it is possible at the start-up (training) stage.

    They created a simple application flattering, which is just nowhere to be wrong, and they checked with it that the connection works.

    If any of these steps have made mistakes, write, think further!



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2