How to connect to SQL Server with VB.NET?

Asked

Viewed 414 times

2

I’ve tried like 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 executes and returns the server version.

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

Since I am using the same library, I assumed it would work the same way, but in VB.NET it returns me Instance Failure and makes an exception of the type InvalidOperationException on the line

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

Why?

1 answer

4


Strip these 2 bars to separate the instance name.

Moult .\\sqlexpress; for .\sqlexpress; in VB.

In c# or you make "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";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.