Guest User

Untitled

a guest
Sep 19th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 5.04 KB | None | 0 0
  1. Public Class Form2
  2.  
  3.     Private Sub btn_ok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_add.Click
  4.         If txt_usuario.Text = "" Or txt_senha.Text = "" Or txt_confirm.Text = "" Then
  5.             MessageBox.Show("Preencha os Campos")
  6.             txt_usuario.Clear()
  7.             txt_senha.Clear()
  8.             txt_confirm.Clear()
  9.         Else
  10.             If txt_senha.Text = txt_confirm.Text Then
  11.                 'Cria um objeto conexão, passando a string de conexão
  12.                 'dim conexao as new sqlconnection("Dara Source=NomedoMeuServidor; initial Catalog=NomeDoMeuBanco; User ID= MeuUsuario;Password=MinhaSenha)
  13.                 Dim conexao As New SqlConnection("Data Source=VSTUDIO-SQL;Initial Catalog=3if3;Integrated Security=True")
  14.                 'variaveis que futuramente irao armazenar os dados advindos do banco
  15.                 Dim usuarioBanco As String = ""
  16.                 Dim senhaBanco As String = ""
  17.                 'esse é o comando select que vai trazer os dados do banco
  18.                 Dim sql As String
  19.                 'SELECT [nm_usuario],[cd_senha]FROM [3if3].[dbo].[Tabela]
  20.                 sql = "SELECT nm_usuario, cd_senha FROM tabela WHERE nm_usuario='" & txt_usuario.Text & "'AND cd_senha='" & txt_senha.Text & "'"
  21.                 'cria um novo comando, passando o sql e a conexao criada
  22.                 Dim comando As New SqlCommand(sql, conexao)
  23.                 'cria um objeto datareader que vai receber os dados lidos
  24.                 Dim dr As SqlDataReader
  25.                 'abrindo a conexão com o banco
  26.                 conexao.Open()
  27.                 'executando a leitura
  28.                 dr = comando.ExecuteReader()
  29.                 ' o metodo READ do dataReader retorna um boolean, que diz se existe proximo valor no caso abaixo, enquanto existirem resultados ele
  30.                 'estara rodando e em cada loop o dr vai representar uma linha diferente do resultado no nosso caso provavelmente
  31.                 'só irá haver um loop portanto estou inserindo direto em variaveis e não em um array
  32.                 While (dr.Read())
  33.                     'getString pois o valor é string, o numero inteiro ai significa o posicionamento da coluna no query executado
  34.                     usuarioBanco = dr.GetString(0) 'GetString pois é variavel alfanumerica
  35.                     senhaBanco = dr.GetString(1) 'poderia ser gtint, getboolean
  36.  
  37.                 End While
  38.                 'aqui fecha a conexão caso surja essa duvida!! hahaha
  39.                 'não  reader pois ao contrario do datasett o datareader não trabalha com dados desconectados, então enquanto precisar de ler o datareader precisará que a conexão esteja aberta
  40.                 conexao.Close()
  41.                 'para evitar um sqlinject estamos comparando em um if simples se realmente o que esta no textbox bate com o que vem do banco a função trim retira possiveis espaços em branco no começo e no final da string
  42.                 If usuarioBanco.Trim() = txt_usuario.Text.Trim() And senhaBanco.Trim() = txt_senha.Text.Trim And txt_usuario.Text <> "" And txt_senha.Text <> "" Then
  43.                     lbl_msg.Visible = True
  44.                     lbl_msg.ForeColor = Color.Green
  45.                     lbl_msg.Text = "Entrada Permitida"
  46.                     txt_usuario.Clear()
  47.                     txt_senha.Clear()
  48.                 Else
  49.                     lbl_msg.Visible = True
  50.                     lbl_msg.ForeColor = Color.Red
  51.                     lbl_msg.Text = "ACESSO NEGADO!!!"
  52.                     txt_usuario.Clear()
  53.                     txt_senha.Clear()
  54.                     txt_usuario.Focus()
  55.                 End If
  56.                 If txt_senha.Text = txt_confirm.Text Then
  57.                     Dim conexao2 As New SqlConnection("Data Source=VSTUDIO-SQL;Initial Catalog=3if3;Integrated Security=True")
  58.                     Dim sql2 As String
  59.                     'INSERT INTO [3if3].[dbo].[Tabela][nm_usuario],[cd_senha]) VALUES*( ('admin', 'admin')
  60.                     sql = "INSERT INTO tabela (nm_usuario, cd_senha) VALUES ('" & txt_usuario.Text & "','"
  61.                     Dim comando2 As New SqlCommand(sql2, conexao2)
  62.                     conexao.Open()
  63.                     Dim linhasAfetadas As Integer = 0
  64.                     linhasAfetadas = comando.ExecuteNonQuery()
  65.                     conexao.Close()
  66.                     If linhasAfetadas <> 0 Then
  67.                         lbl_msg.ForeColor = Color.Green
  68.                         lbl_msg.Text = "Cadastrado!"
  69.                         btn_add.Visible = False
  70.                     Else
  71.                         lbl_msg.ForeColor = Color.Red
  72.                         lbl_msg.Text = "ERRO!!!"
  73.                     End If
  74.  
  75.                 Else
  76.                     lbl_msg.ForeColor = Color.Red
  77.                     lbl_msg.Text = "Senhas Diferentes"
  78.                     txt_usuario.Clear()
  79.                     txt_senha.Clear()
  80.                     txt_confirm.Clear()
  81.                     txt_usuario.Focus()
  82.                 End If
  83.             End If
  84.         End If
  85.     End Sub
Add Comment
Please, Sign In to add comment