PostgresSql connection with Visual Studio [closed]

-2

Good night, I need to connect to the database with visual studio C #, but I'm not sure how to do it and the materials I find are a bit confusing, if anyone can help I'll be grateful, I'm developing a project for a system related to nutrition and I already have the deadline bursting due to this fact and everything. Thank you in advance!

    
asked by anonymous 11.04.2018 / 02:52

1 answer

0

You can create a Class for this:

Only before that we'll add a ConnectionStrings to App.config of your project. Once you have found and opened 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>

Once this is done 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 is 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}");
        }
    }
}
    
11.04.2018 / 19:06