Connect to a local database c#

Asked

Viewed 229 times

0

What is the correct syntax of Sqlconnection to connect to a local database? I think it’s something like this!!

    SqlConnection liga = new SqlConnection(@"Data Source=(LocalDB)\v11.0;
                      AttachDbFilename=|DataDirectory|\BaseDeDados.mdf;
                      Integrated Security=True;
                      Connect Timeout=30");
  • to see the connection string syntax, go to: https://www.connectionstrings.com/ and to see the syntax of SqlConnection access: https://msdn.microsoft.com/pt-br/library/system.data.sqlclient.sqlconnection(v=vs.110). aspx

1 answer

0


Use this way, is the most recommended using keyword using.

var connectionString = @"Data Source=(LocalDB)\v11.0;
                      AttachDbFilename=|DataDirectory|\BaseDeDados.mdf;
                      Integrated Security=True;
                      Connect Timeout=30";

using (SqlConnection con = new SqlConnection(connectionString))
{
    con.Open();

    using (SqlCommand command = new SqlCommand("SELECT * FROM Table", con))
    using (SqlDataReader reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            // Leitura do seu Reader
        }
    }
}

Browser other questions tagged

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