Database connection in Windows Form?

Asked

Viewed 769 times

0

How to make/call the database connection in Windows Form? Knowing that the database configuration is in the app.config

  • Do you have any code?

  • I do! I did it that way:

1 answer

5


You can do as follows to use the resource you need:

  • Declare the namespace: using System.Configuration;

Below is the class I use to open the connection.

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;

namespace Framework
{
     public class ConexaoBD
     {
          // Variável global da classe
          private static SqlConnection strConexao = default(SqlConnection);

         /// <summary>
         /// Método cria e abre a conexão com o banco de dados
         /// </summary>
         /// <param name="pstrMsg"></param>
         /// <param name="pbooRetorno"></param>
         /// <returns>SqlConnection</returns>
         public static SqlConnection CriarConexao(out String pstrMsg, out Boolean pbooRetorno)
         {
             pstrMsg = default(String);
             pbooRetorno = default(Boolean);      

             try
             {
                 /* 
                   - [NomeDaStringDeConexao]: é o nome configurado dentro do arquivo app.config na string de conexão
                   - A classe ConfigurationManager.ConnectionStrings, busca direto do meu app.config a minha string de conexão.
                 */
                 strConexao = new SqlConnection(ConfigurationManager.ConnectionStrings[NomeDaStringDeConexao].ConnectionString);

                 if (strConexao.State == ConnectionState.Closed)
                 {
                     strConexao.Open();

                     pbooRetorno = true;
                 }
             }
             catch (SqlException ex)
             {
                 pstrMsg = ex.Message;

                 pbooRetorno = false;
             }
             return strConexao;
         }
     }
 }

Browser other questions tagged

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