Where to put the connection string to the database?

1

I have the form:

Thedatabaseandtheregistrationtablehavealreadybeencreated,IamusingwampserverandMySQLWorkbench.

Myquestioniswheretoputtheconnectionstring:

MySqlConnectionconn=newMySqlConnection("Persist Security Info=False;Server=localhost;Database=banco_teste;uid=root;pwd=;");

Currently my code looks 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 inside the btnGravar_Click method:

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

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

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

    
asked by anonymous 05.07.2014 / 23:13

1 answer

3

The connection configuration 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();
        }
    }
}

Note: A tip I give as it is an Object Oriented language, transport this to a better model with Dal and BLL than opening it up every time you have a new form.

    
05.07.2014 / 23:20