Advertisement
usernam3_

[Debug] Conexão MySQL / C#

Aug 30th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.79 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using MySql.Data.MySqlClient;
  11.  
  12. namespace teste
  13. {
  14.     public partial class Form1 : Form
  15.     {
  16.         private System.Windows.Forms.DataGrid datagrid;
  17.         private MySqlConnection conexao;
  18.         private MySqlDataAdapter adapter;
  19.         private DataSet dataset;
  20.  
  21.         public Form1()
  22.         {
  23.             InitializeComponent();
  24.  
  25.             dataset = new DataSet();
  26.  
  27.             conexao = new MySqlConnection("Persist Security Info=False;" +
  28.                 "                          server=localhost;" +
  29.                 "                          database=teste;" +
  30.                 "                          uid=root;" +
  31.                 "                          pwd=pass");
  32.  
  33.             try
  34.             {
  35.                 conexao.Open();
  36.             }
  37.             catch(Exception e)
  38.             {
  39.                 MessageBox.Show(e.Message.ToString());
  40.             }
  41.  
  42.             // Verifica se a conexao esta aberta
  43.             if(conexao.State == ConnectionState.Open)
  44.             {
  45.                 // Cria um adapter para acessar a tabela Clientes
  46.                 adapter = new MySqlDataAdapter("SELECT * FROM Clientes", conexao);
  47.                 // Preenche o dataset via adapter
  48.                 adapter.Fill(dataset,"Clientes");
  49.                 // Atribui o resultado a propriedade DataSource do DataGrid
  50.                 datagrid.DataSource = dataset;
  51.                 datagrid.DataMember = "Clientes";
  52.             }
  53.             if(conexao.State == ConnectionState.Open)
  54.             {
  55.                 conexao.Close();
  56.             }
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement