How to connect to SQL Server with VB.NET?

2

I have tried some five tutorials.

See the code in C #

        string minhaString = "Server=.\sqlexpress;Trusted_Connection=true;" +
               "Timeout=10;" + 
               "Database =bdcadastro;";

        SqlConnection minhaConexao = new SqlConnection(minhaString);


        try
        {
            minhaConexao.Open();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        finally 
        {
            Console.WriteLine("Versão do servidor: " + myConnection.ServerVersion);
        }

The code runs and returns the version of the server.

VB.NET:

    Dim minhaString As String = "Server=.\sqlexpress;" &
        "Trusted_Connection=true;Timeout=10;Database=bdcadastro;"
    Dim minhaConexao = New SqlConnection(minhaString)

    Try
        minhaConexao.Open()
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    Finally
        Console.WriteLine("Server version is: " + myConnection.ServerVersion)
    End Try

As I'm using the same library, I assumed it would work the same, but in VB.NET it returns me Instance Failure and throws an exception of type InvalidOperationException on line

Console.WriteLine("Server version is: " + myConnection.ServerVersion)

Why?

    
asked by anonymous 11.11.2015 / 00:36

1 answer

4

Remove these 2 slashes to separate the instance name.

Changes from .\sqlexpress; to .\sqlexpress; in VB.

In C # or you do "escape" from certain characters or use @ before to indicate that everything inside the string is a" scape sequence ".

var instance = ".\sqlexpress";

or

var instance = @".\sqlexpress";
    
11.11.2015 / 06:22