Postgressql connection with Visual Studio

Asked

Viewed 50 times

-2

Good evening, I need to connect the database with the visual studio c#, but I don’t understand exactly how to accomplish and the materials I find are a bit confusing, if anyone can help I would be grateful, I’m developing a project for a nutrition-related system and I’m already on a deadline due to this fact and everything. Thank you in advance!

  • which database? You have to say what you are using or which one you want to use.

  • The database I defined yesterday is sql Server. But where I worked they had a specific webserver to make the Connections, so the doubt, if you can help me I will be very grateful, this part is catching me a lot. Thank you!

  • you’ve heard of connection string?

  • Connection string already, but what happens, I work as a developer as a whole has 5 months, where I worked for 3 months their webservice was sqld.Executenonquery("code of the bank"); However I went to see and it is different and the explanations so far are a little confused, did not give me a north you know?

1 answer

0


you can create a Class for this:

Only before that we’ll add one ConnectionStrings at the App.config of your project. Once located and opened the App.config before the closing tag <\configuration>, add:

<connectionStrings>
      <add name="CaminhoSqlSever" 
           providerName="System.Data.SqlClient"
           connectionString="Server=Nome do seu Server;
                             Database=Nome do seu Banco;
                             User Id=seu usuário;
                             Password=Seu password;"/>
</connectionStrings>

Done this add the necessary references to the project:

using System.Configuration; //-> Com ele podemos acessar a ConnectionString criada no `App.config`
using System.Data.SqlClient; 

There are several ways to create this class, below follows a simple example.

class ConexaoDB
{
    //-->Variavel que armazena a conexão.
    SqlConnection Con;

    //Propriedade que encapsula e retorna a conexão.
    public SqlConnection Conexao => Con;

    //Propriedade que retorna a string da conexão armazenada no arquivo de configurações.
    public string StrConexao => ConfigurationManager.ConnectionStrings["CaminhoSqlSever"].ConnectionString;

    public ConexaoDB()
    {
        try
        {
            Con = new SqlConnection(StrConexao);
        }
        catch (SqlException erro)
        {
            MessageBox.Show($"Ocorreu um erro: {erro.message}");
        }
    }
}

Browser other questions tagged

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