Where to place the connection string with the database?

Asked

Viewed 3,634 times

1

I have the form:

formulario Cadastro

Already created the database and table for registration, I am using wampserver and Mysql Workbench.

My question is where to place the connection string:

MySqlConnection conn = new MySqlConnection("Persist Security Info=False;Server=localhost;Database=banco_teste;uid=root;pwd=;");

Currently my code is like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;


namespace teste_DB
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            MySqlConnection conn = new MySqlConnection("Persist Security Info=False;Server=localhost;Database=banco_teste;uid=root;pwd=;");
        }

        private void btnGravar_Click(object sender, EventArgs e)
        {

        }
    }
}

When I try to open the connection within the method btnGravar_Click:

private void btnGravar_Click(object sender, EventArgs e)
{
    conn.Open();
}

Visual Studio returns me error stating that the name conn does not exist in the context.

Where I can declare the connection string so I can open the connection whenever I want?

1 answer

3


The connection setting can be placed in the App.Config file, in connectionStrings with the name of Mysqlconnection.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>    
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>    
    <add name="MysqlConnection" 
         connectionString="Server=localhost;Database=testdb;Uid=root;Pwd=senha;" 
         providerName="Mysql.Data.MysqlClient"/>  
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

To use this setting can be done like this:

MySqlConnection conn = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MysqlConnection"].ConnectionString);

The variable conn to be accessed in this class must be created outside the constructor, as an example below:

namespace teste_DB
{
    public partial class Form1 : Form
    {
        private MySqlConnection conn = null;
        public Form1()
        {
            InitializeComponent();
            //ta assim  
            //conn = new MySqlConnection("Persist Security Info=False;Server=localhost;Database=banco_teste;uid=root;pwd=;");
           //pode ficar assim com a connectionStrings do App.config
           conn = new MysqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MysqlConnection"].ConnectionString);
        }

        private void btnGravar_Click(object sender, EventArgs e)
        {
            conn.Open();
        }
    }
}

Obs: A hint that I give as it is an Object-Oriented language, carry it to a better model with Dal and BLL than keep opening it every time it has a new form.

Browser other questions tagged

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