Ir para conteúdo
Fórum Script Brasil
  • 0

Insert Into


Gabriel Cabral

Pergunta

Por favor me ajudem !!!!!

tenho um formulario de cadastro d usuarios e está tudo certo....acho.......

a conexao está feita.....

quando vou testar o programa, preencho todos os campos e clico em gravar dados..

os campos se esvaziam pra poder cadastrar mais....

ateh aí tudo bem....

mas quando vou ao banco de dados, nenhum cadastro que fiz está lá...

o banco de dados se encontra vazio...sem nenhum registro...

o que está acontecendo???

o que está errado???

aqui está a codificação......se alguém tiver a paciencia d analisar e me ajudar, agradeço muito

Dim vInclusao As Boolean

Private Sub Form_KeyPress(KeyAscii As Integer)

If KeyAscii = vbKeyReturn Then

SendKeys "{Tab}"

KeyAscii = 0

End If

End Sub

Private Sub Form_Load()

Me.Left = (frmBiblio.ScaleWidth - Me.Width) / 2

Me.Top = (frmBiblio.ScaleHeight - Me.Height) / 2

End Sub

Private Sub Toolbar1_ButtonClick(ByVal Button As MSComctlLib.Button)

Select Case Button.Index

Case 1

GravarDados

Case 2

LimparTela

Case 3

ExcluirRegistro

Case 4

Unload Me

End Select

End Sub

Private Sub txtCodUsuario_LostFocus()

Dim cnnComando As New ADODB.Command

Dim rsSelecao As New ADODB.Recordset

On Error GoTo errSelecao

If Val(txtCodUsuario.Text) = 0 Then

MsgBox "Não foi digitado um código válido, verifique.", vbExclamation + vbOKOnly + vbApplicationModal, "Erro"

Exit Sub

End If

With cnnComando

.ActiveConnection = cnnBiblioteca

.CommandType = adCmdText

.CommandText = "SELECT * FROM Usuarios WHERE CodUsuario = " & txtCodUsuario.Text & ";"

Set rsSelecao = .Execute

End With

With rsSelecao

If .EOF And .BOF Then

LimparDados

vInclusao = True

Else

txtNomeUsuario.Text = !NomeUsuario

txtEndereco.Text = !Endereco

txtCidade.Text = !Cidade

txtEstado.Text = !Estado

txtCEP.Text = !CEP

txtDDD.Text = Empty & !DDD

txtTelefone.Text = Empty & !Telefone

vInclusao = False

Toolbar1.Buttons(3).Enabled = True

End If

End With

Saida:

Set rsSelecao = Nothing

Set cnnComando = Nothing

Exit Sub

errSelecao:

With Err

If .Number <> 0 Then

MsgBox "Houve um erro na recuperação do registro solicitado.", vbExclamation + vbOKOnly + vbApplicationModal, "Aviso"

.Number = 0

GoTo Saida

End If

End With

End Sub

Private Sub LimparDados()

txtNomeUsuario.Text = ""

txtEndereco.Text = ""

txtCidade.Text = ""

txtEstado.Text = ""

txtCEP.Text = ""

txtDDD.Text = ""

txtTelefone.Text = ""

End Sub

Private Sub GravarDados()

Dim cnnComando As New ADODB.Command

Dim vConfMsg As Integer

Dim vErro As Boolean

On Error GoTo errGravacao

vConfMsg = vbExclamation + vbOKOnly + vbSystemModal

vErro = False

If txtNomeUsuario.Text = "" Then

MsgBox "O campo Nome não foi preenchido.", vConfMsg, "Erro"

vErro = True

End If

If txtEndereco.Text = "" Then

MsgBox "O campo Enderço não foi preenchido.", vConfMsg, "Erro"

vErro = True

End If

If txtCidade.Text = "" Then

MsgBox "O campo Cidade não foi preenchido.", vConfMsg, "Erro"

vErro = True

End If

If txtEstado.Text = "" Then

MsgBox "O campo Estado não foi preenchido.", vConfMsg, "Erro"

vErro = True

End If

If txtCEP.Text = "" Then

MsgBox "O campo CEP não foi preenchido.", vConfMsg, "Erro"

vErro = True

End If

If vErro Then Exit Sub

With cnnComando

.ActiveConnection = cnnBiblioteca

.CommandType = adCmdText

If vInclusao Then

.CommandText = "INSERT INTO Usuarios " & _

"(CodUsuario, NomeUsuario, Endereco, Cidade, " & _

"Estado, CEP, DDD, Telefone) VALUES ('" & _

txtCodUsuario.Text & ",'" & _

txtNomeUsuario.Text & "','" & _

txtEndereco.Text & "','" & _

txtCidade.Text & "','" & _

txtEstado.Text & "','" & _

txtCEP.Text & "','" & _

txtDDD.Text & "','" & _

txtTelefone.Text & "');"

Else

.CommandText = "UPDATE Usuarios SET " & _

"NomeUsuario = '" & txtNomeUsuario.Text & "'," & _

"Endereco = '," & txtEndereco.Text & "'," & _

"Cidade = '," & txtCidade.Text & "'," & _

"Estado = '," & txtEstado.Text & "'," & _

"CEP = '," & txtCEP.Text & "'," & _

"DDD = '," & txtDDD.Text & "'," & _

"Telefone = '," & txtTelefone.Text & "' " & _

"WHERE CodUsuario = " & txtCodUsuario.Text & ";"

.Execute

End If

End With

MsgBox "Gravação concluída com sucesso.", vbApplicationModal + vbInformation + vbOKOnly, "Gravação OK"

LimparTela

Saida:

Set cnnComando = Nothing

Exit Sub

errGravacao:

With Err

If .Number <> 0 Then

MsgBox "Houve um erro durante a gravação dos dados na tabela.", vbExclamation + vbOKOnly + vbApplicationModal, "Erro"

.Number = 0

GoTo Saida

End If

End With

End Sub

Private Sub LimparTela()

LimparDados

Toolbar1.Buttons(3).Enabled = False

txtCodUsuario.Text = ""

txtCodUsuario.SetFocus

End Sub

Private Sub ExcluirRegistro()

Dim cnnComando As New ADODB.Command

Dim vOk As Integer

On Error GoTo errExclusao

vOk = MsgBox("Confirma a exclusão desse registro?", vbApplicationModal + vbDefaultButton2 + vbQuestion + vbYesNo, "Exclusão")

If vOk = vbYes Then

With cnnComando

.ActiveConnection = cnnBiblioteca

.CommandType = adCmdText

.CommandText = "DELETE FROM Usuarios WHERE CodUsuario = " & _

txtCodUsuario.Text & ";"

.Execute

End With

MsgBox "Registro excluído com sucesso.", vbApplicationModal + vbInformation + vbOKOnly, "Exclusão OK"

LimparTela

End If

Saida:

Set cnnComando = Nothing

Exit Sub

errExclusao:

With Err

If .Number <> 0 Then

MsgBox "Houve um erro durante a exclusão do registro.", vbExclamation + vbOKOnly + vbApplicationModal, "Erro"

.Number = 0

GoTo Saida

End If

End With

End Sub

Link para o comentário
Compartilhar em outros sites

4 respostass a esta questão

Posts Recomendados

  • 0

Opa.. beleza?

Você não fechou as aspas simples da primeira variável no Insert

('" & _

txtCodUsuario.Text & "

E outra, aquele ; no final é realmente necessário? porque nunca utilizei ele e não tive problema nenhum :D

Bom, eu dei uma olhada rápida só no código. Pode não ser isso... Mas espero que ajude :D

falou

Link para o comentário
Compartilhar em outros sites

  • 0

Está faltando uma aspa simples no código da apostila Microsoft Visual Basic 6 de Luís Carlos, rotina Gravar Dados pg. 77:

Errado: txtCodUsuario.Text & ",'"

Certo: txtCodUsuario.Text & "','"

Eu estava estudando nela também e achei o erro. Agora funcionou a inclusão.

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,2k
    • Posts
      652k
×
×
  • Criar Novo...