Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Olá pessoal estou com o seguinte problema aqui não consigo navegar entre os campos com MyRS.MoveNext apenas carrego o primeiro registro.Será que é problema com o MySQL 5 ou com a Linguagem que estou usando que na situação é VB 6.Desde já agradeço a atenção de todos.
Mostra como você está fazendo.
O problema acontece quando eu utilizo uma combo acaba dando problemano botão de navegação eu coloco assim: cmd_proximo ()click If rs.EOF = False Then rsL.MoveNext If rs.EOF Then rs.MoveLast End If Else If rs.BOF Then rs.MoveLast End If codigo pra carregar a combo: com dados de outra tabela cmbCidade.ClearSet rs = New RecordsetIf rs.State = adStateOpen Then rs.Closers.Open "SELECT Cidade FROM tb_cidades ORDER BY Cidade", Database, adOpenDynamic, adLockOptimisticWhile Not rs.EOFcmbCidade.AddItem rs!Cidaders.MoveNextWendSet rs = Nothing____________________________carrega registro atual na propriedade text da combocmbCidade.text = rs!CidadeSerá que para navegar pelos registros é necessário outro código pois pretendo utilizar a combo para selecionar a cidade para o registro atual e manter a cidadeescolhida para o registro em uso na propriedade text da combo.
Está dando erro nesse Loop? Não está incluindo todas as cidades?Caso seja isso verifica se há mais de uma cidade na tabela mesmo, pois o código está corretoE para que a RS carregada no evento da combo seja a mesma do botão você tem que declará-la na parte general (acima de todos os eventos, no topo da área de códigos).
Está dando erro nesse Loop? Não está incluindo todas as cidades?Caso seja isso verifica se há mais de uma cidade na tabela mesmo, pois o código está corretoE para que a RS carregada no evento da combo seja a mesma do botão você tem que declará-la na parte general (acima de todos os eventos, no topo da área de códigos).
Muito Obrigado pela ajuda valew muito mesmoNa tabela cidades eu possuo até o momento 5 cidades cadastradas e na combo aparece apenas 3 que é a quantidade de cadastros que eu tenho na tabela alunos que é onde eu queria inserir a cidade vinda da outra tabela.Será que a tabela cidades só vai carregar os campos de acordo com a quantidade de registros que existem na tabela de alunos que no caso são apenas 3 e na tabela cidade 5 e a combo mostra apenas três.Também estava pensando não sei como fazer mais acho que algo assim também poderia ajuda criar um listview em outro form onde irá ter a tabela cidades e colocar um botão no cadastro de alunos que qdo o usuario for inserir uma cidade para o aluno ele possa clique neste botão e abra o form com o listview e selecione a cidade que irá ser vinculada a tabela alunos e aparecer em um textbox. não sei se é mais simples, mais é que até agora não obtive muito sucesso com a combo.
Como eu disse no outro post essa sua rotina para carregar:
cmbCidade.ClearSet rs = New RecordsetIf rs.State = adStateOpen Then rs.Closers.Open "SELECT Cidade FROM tb_cidades ORDER BY Cidade", Database, adOpenDynamic, adLockOptimisticWhile Not rs.EOFcmbCidade.AddItem rs!Cidaders.MoveNextWendSet rs = NothingEstá, aparentemente, correta. Não há porque não incluir todos os registros na combo.
Mas só para desencargo de consciência tenta colocar mais registros na tabela de alunos para ver se realmente está influenciando em algo. Não consigo pensar em como ou porque isso ocorreria.
Quanto ao outro modo de escolher a cidade a combo é a melhor opção. Poupando você de cirar outro form com outros objetos e mais codificação.
>
Como eu disse no outro post essa sua rotina para carregar:
cmbCidade.ClearSet rs = New RecordsetIf rs.State = adStateOpen Then rs.Closers.Open "SELECT Cidade FROM tb_cidades ORDER BY Cidade", Database, adOpenDynamic, adLockOptimisticWhile Not rs.EOFcmbCidade.AddItem rs!Cidaders.MoveNextWendSet rs = NothingEstá, aparentemente, correta. Não há porque não incluir todos os registros na combo.Mas só para desencargo de consciência tenta colocar mais registros na tabela de alunos para ver se realmente está influenciando em algo. Não consigo pensar em como ou porque isso ocorreria.Quanto ao outro modo de escolher a cidade a combo é a melhor opção. Poupando você de cirar outro form com outros objetos e mais codificação.
Eu também prefiro a combo outra coisa que eu ia falar pra você é que no load do form eu também carrego a tabela cidades juntamente com outras 3 da seguinte forma: Set rsMySQL = New ADODB.Recordset rsMySQL.CursorType = adOpenStatic rsMySQL.CursorLocation = adUseClient rsMySQL.LockType = adLockPessimistic rsMySQL.Source = "SELECT tb_alunos.*, tb_cidades.Cidade, tb_empresas.Empresa, tb_bairros.*, tb_cidades.Estado FROM tb_alunos INNER JOIN tb_bairros ON tb_alunos.Id_Bairro = tb_bairros.Id_Bairro INNER JOIN tb_cidades ON tb_alunos.Id_Cidade = tb_cidades.Id_Cidade INNER JOIN tb_empresas ON tb_alunos.Id_Empresas = tb_empresas.Id_Empresas" rsMySQL.ActiveConnection = adoDataConn rsMySQL.OpenE para a combo eu utilizo uma private sub preenchecombo() e a já tentei carregar no load do form e no evento gotfocus da combo mais em ambas não houve sucesso.coloca rs.movefirst antes do loop
coloca rs.movefirst antes do loop
Valew pela ajuda mais já fiz desse modo e também não deu certo
Sou iniciante ainda com isso precisamente 3 semanas nesse mundo de programação VB6 - MySQL será que eu fiz alguma coisa errada com o código abaixo que estou utilizando pra fazer a aplicação, pois só da erro quando uso as combobox ai quando eu uso texbox funciona apesar que ainda não testei como salvar.
Option ExplicitPrivate WithEvents adoDataConn As ADODB.ConnectionPrivate WithEvents rsMySQL As ADODB.RecordsetDim mblnAddMode As BooleanDim ctlControle As ControlDim strConnect As StringDim strProvider As StringDim strDataSource As StringDim strDataBaseName As StringDim usr_id As StringDim pass As StringDim mySqlIP As StringPrivate Sub cmbCidade_GotFocus() cboCidade.ClearSet rsMySQL = New RecordsetIf rsMySQL.State = adStateOpen Then rsMySQL.ClosersMySQL.Open "SELECT tb_cidades.Cidade FROM tb_cidades WHERE tb_cidades.Cidade = tb_cidades.Cidade", adoDataConn, adOpenDynamic, adLockOptimisticWhile Not rsMySQL.EOFcboCidade.AddItem rsMySQL!CidadersMySQL.MoveNextWendSet rsMySQL = NothingErro: 'se houver erros faz o tratamentoIf Err.Number <> 0 Then MsgBox ("Erro #: " & Str(Err.Number) & Err.Description) Exit SubEnd IfEnd SubPrivate Sub cboEmpresa_GotFocus()cboEmpresa.ClearSet rsMySQL = New RecordsetIf rsMySQL.State = adStateOpen Then rsMySQL.ClosersMySQL.Open "SELECT tb_empresas.Empresa From tb_empresas Where tb_empresas.Empresa = tb_empresas.Empresa ORDER BY tb_empresas.Empresa", adoDataConn, adOpenDynamic, adLockOptimisticWhile Not rsMySQL.EOFcboEmpresa.AddItem rsMySQL!EmpresarsMySQL.MoveNextWendSet rsMySQL = NothingErro: 'se houver erros faz o tratamentoIf Err.Number <> 0 Then MsgBox ("Erro #: " & Str(Err.Number) & Err.Description) Exit SubEnd IfEnd SubPrivate Sub cmdAbreConexao_Click() mySqlIP = "localhost" usr_id = "root" ' pass = "flaviojr" strConnect = "Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=sunrise_db;User=root;Password=flaviojr;Option=3;" Set adoDataConn = New ADODB.Connection adoDataConn.CursorLocation = adUseClient adoDataConn.Open strConnect Set rsMySQL = New ADODB.Recordset rsMySQL.CursorType = adOpenStatic rsMySQL.CursorLocation = adUseClient rsMySQL.LockType = adLockPessimistic rsMySQL.Source = "SELECT tb_alunos., tb_cidades.Cidade, tb_empresas.Empresa, tb_bairros., tb_cidades.Estado FROM tb_alunos INNER JOIN tb_bairros ON tb_alunos.Id_Bairro = tb_bairros.Id_Bairro INNER JOIN tb_cidades ON tb_alunos.Id_Cidade = tb_cidades.Id_Cidade INNER JOIN tb_empresas ON tb_alunos.Id_Empresas = tb_empresas.Id_Empresas" rsMySQL.ActiveConnection = adoDataConn rsMySQL.Open cmdAbreConexao.Enabled = False cmdFechaConexao.Enabled = True HabilitaNavegacao cmdInclui.Enabled = True cmdExclui.Enabled = True cmdEdita.Enabled = True End SubPrivate Sub cmdFechaConexao_Click() adoDataConn.Close Set adoDataConn = Nothing cmdFechaConexao.Enabled = False cmdAbreConexao.Enabled = True Call LimparTexto End SubPublic Sub PreencheCombo()cboCidade.ClearSet rsMySQL = New RecordsetIf rsMySQL.State = adStateOpen Then rsMySQL.CloseSet rsMySQL = NothingrsMySQL.Open "SELECT tb_cidades.Cidade FROM tb_cidades WHERE tb_cidades.Cidade = tb_cidades.Cidade", adoDataConn, adOpenDynamic, adLockOptimisticDo While Not rsMySQL.EOFcboCidade.AddItem rsMySQL!CidadersMySQL.MoveNextLoop'WendSet rsMySQL = NothingErro: 'se houver erros faz o tratamentoIf Err.Number <> 0 Then MsgBox ("Erro #: " & Str(Err.Number) & Err.Description) Exit SubEnd IfEnd SubPrivate Sub LimparTexto()txtNome.Text = ""txtRua.Text = ""txtDataNascimento.Text = ""txtNatural.Text = ""txtReligiao.Text = ""txtSexo.Text = ""txtRG.Text = ""txtCPF.Text = ""txtProfissao.Text = ""txtEmpresa.Text = ""txtEmail.Text = ""txtDDD.Text = ""txtTelefone.Text = ""txtCelular.Text = ""txtTelefoneComercial.Text = ""txtNumero.Text = ""txtComplemento.Text = ""txtCEP.Text = ""txtBairro.Text = ""txtCidade.Text = ""txtEstado.Text = ""txtAnotacoes.Text = ""txtEmail.Text = ""End SubPrivate Sub CarregaRegistros()On Error Resume Next If rsMySQL.BOF = True Or rsMySQL.EOF = True Then Exit Sub End If txtId_Aluno.Text = rsMySQL!Id_Aluno & "" txtNome.Text = rsMySQL!Nome & "" txtRua.Text = rsMySQL!Rua & "" txtDataNascimento.Text = rsMySQL!DataNascimento & "" txtNatural.Text = rsMySQL!Natural & "" txtReligiao.Text = rsMySQL!Religiao & "" txtSexo.Text = rsMySQL!Sexo & "" txtRG.Text = rsMySQL!RG & "" txtCPF.Text = rsMySQL!CPF & "" txtProfissao.Text = rsMySQL!Profissao & "" txtEmpresa.Text = rsMySQL!Empresa & "" txtEmail.Text = rsMySQL!Email & "" txtDDD.Text = rsMySQL!DDD & "" txtTelefone.Text = rsMySQL!Telefone & "" txtCelular.Text = rsMySQL!Celular & "" txtTelefoneComercial.Text = rsMySQL!TelefoneComercial & "" txtNumero.Text = rsMySQL!Numero & "" txtComplemento.Text = rsMySQL!Complemento & "" txtCEP.Text = rsMySQL!CEP & "" txtBairro.Text = rsMySQL!Bairro & "" txtCidade.Text = rsMySQL!Cidade & "" txtEstado.Text = rsMySQL!Estado & "" txtAnotacoes.Text = rsMySQL!Anotacoes & "" txtEmail.Text = rsMySQL!Email & "" cboCidade.Text = rsMySQL!Cidade & "" cboEmpresa.Text = rsMySQL!Empresa & ""End SubPrivate Sub Form_Load() DesabilitaNavegacao cmdInclui.Enabled = False cmdExclui.Enabled = False cmdEdita.Enabled = False End SubPrivate Sub lvButtons_H3_Click()frmCidades.ShowEnd SubPrivate Sub rsMySQL_MoveComplete(ByVal adReason As ADODB.EventReasonEnum, ByVal pError As ADODB.Error, adStatus As ADODB.EventStatusEnum, ByVal pRecordset As ADODB.Recordset) If mblnAddMode = False Then 'se nao estiver no modo de inclusão 'carrega os controles com os dados Call CarregaRegistros End IfEnd SubPrivate Sub cmdPrimeiro_Click() If rsMySQL.BOF = False Then rsMySQL.MoveFirst ElseIf rsMySQL.BOF = True _ And rsMySQL.EOF = True Then MsgBox "Não há dados no Arquivo!", , "Sem Dados !" End If End SubPrivate Sub cmdUltimo_Click() If rsMySQL.EOF = False Then rsMySQL.MoveLast ElseIf rsMySQL.BOF = True _ And rsMySQL.EOF = True Then MsgBox "Não há dados no Arquivo!", , "Sem Dados !" End IfEnd SubPrivate Sub cmdAnterior_Click() If rsMySQL.BOF = False Then rsMySQL.MovePrevious If rsMySQL.BOF = True Then rsMySQL.MoveFirst End If Else If rsMySQL.EOF Then MsgBox "Não há dados no Arquivo!", , "Sem Dados !" Else rsMySQL.MoveFirst End If End If End SubPrivate Sub cmdProximo_Click() If rsMySQL.EOF = False Then rsMySQL.MoveNext If rsMySQL.EOF Then rsMySQL.MoveLast End If Else If rsMySQL.BOF Then MsgBox "Não há dados no Arquivo!", , "Sem Dados !" Else rsMySQL.MoveLast End If End IfEnd SubPrivate Sub DesabilitaNavegacao() cmdPrimeiro.Enabled = False cmdUltimo.Enabled = False cmdProximo.Enabled = False cmdAnterior.Enabled = FalseEnd SubPrivate Sub HabilitaNavegacao() cmdPrimeiro.Enabled = True cmdUltimo.Enabled = True cmdProximo.Enabled = True cmdAnterior.Enabled = TrueEnd SubPrivate Sub cmdInclui_Click() If cmdInclui.Caption = "&Incluir" And _ cmdFechaConexao.Enabled = True Then cmdInclui.Caption = "&Cancela" cmdSalva.Enabled = True Call DesabilitaNavegacao mblnAddMode = True Call LimparTexto cmdEdita.Enabled = False cmdExclui.Enabled = False txtNome.Locked = False txtRua.Locked = False txtDataNascimento.Locked = False txtNatural.Locked = False txtReligiao.Locked = False txtSexo.Locked = False txtRG.Locked = False txtCPF.Locked = False txtProfissao.Locked = False txtEmpresa.Locked = False txtEmail.Locked = False txtDDD.Locked = False txtTelefone.Locked = False txtCelular.Locked = False txtTelefoneComercial.Locked = False txtNumero.Locked = False txtComplemento.Locked = False txtCEP.Locked = False txtBairro.Locked = False txtCidade.Locked = False txtEstado.Locked = False txtAnotacoes.Locked = False txtEmail.Locked = False txtNome.SetFocus ElseIf cmdInclui.Caption = "&Cancela" Then cmdInclui.Caption = "&Incluir" cmdSalva.Enabled = False Call HabilitaNavegacao cmdEdita.Enabled = True cmdExclui.Enabled = True mblnAddMode = False txtNome.Locked = True txtRua.Locked = True txtDataNascimento.Locked = True txtNatural.Locked = True txtReligiao.Locked = True txtSexo.Locked = True txtRG.Locked = True txtCPF.Locked = True txtProfissao.Locked = True txtEmpresa.Locked = True txtEmail.Locked = True txtDDD.Locked = True txtTelefone.Locked = True txtCelular.Locked = True txtTelefoneComercial.Locked = True txtNumero.Locked = True txtComplemento.Locked = True txtCEP.Locked = True txtBairro.Locked = True txtCidade.Locked = True txtEstado.Locked = True txtAnotacoes.Locked = True txtEmail.Locked = True If cmdFechaConexao.Enabled = True Then Call CarregaRegistros End If End IfEnd SubPrivate Sub GravaRegistros() rsMySQL!Id_Aluno = txtId_Aluno.Text rsMySQL!Nome = txtNome.Text rsMySQL!Rua = txtRua.Text rsMySQL!DataNascimento = CDate(txtDataNascimento.Text) rsMySQL!Natural = txtNatural.Text rsMySQL!Religiao = txtReligiao.Text rsMySQL!Sexo = txtSexo.Text rsMySQL!RG = txtRG.Text rsMySQL!CPF = txtCPF.Text rsMySQL!Profissao = txtProfissao.Text rsMySQL!Empresa = txtEmpresa.Text rsMySQL!Email = txtEmail.Text rsMySQL!DDD = txtDDD.Text rsMySQL!Telefone = txtTelefone.Text rsMySQL!Celular = txtCelular.Text rsMySQL!TelefoneComercial = txtTelefoneComercial.Text rsMySQL!Numero = txtNumero.Text rsMySQL!Complemento = txtComplemento.Text rsMySQL!CEP = txtCEP.Text rsMySQL!Bairro = txtBairro.Text rsMySQL!Cidade = txtCidade.Text rsMySQL!Estado = txtEstado.Text rsMySQL!Anotacoes = txtAnotacoes.Text rsMySQL!Email = txtEmail.Text End SubPrivate Sub cmdSalva_Click() On Error Resume Next If cmdInclui.Caption = "&Cancela" Then rsMySQL.AddNew End If If txtRG.Text <> "" And txtNome <> "" And txtCPF <> "" Then Call GravaRegistros rsMySQL.Update Else MsgBox "Falta informar dados !!!!", vbCritical, "Incluindo dados" rsMySQL.CancelUpdate mblnAddMode = False Exit Sub End If mblnAddMode = False cmdSalva.Enabled = False If cmdInclui.Caption = "&Cancela" Then cmdInclui.Caption = "&Incluir" End If If cmdEdita.Caption = "&Cancela" Then cmdEdita.Caption = "&Editar" End If txtNome.Locked = True txtRua.Locked = True txtDataNascimento.Locked = True txtNatural.Locked = True txtReligiao.Locked = True txtSexo.Locked = True txtRG.Locked = True txtCPF.Locked = True txtProfissao.Locked = True txtEmpresa.Locked = True txtEmail.Locked = True txtDDD.Locked = True txtTelefone.Locked = True txtCelular.Locked = True txtTelefoneComercial.Locked = True txtNumero.Locked = True txtComplemento.Locked = True txtCEP.Locked = True txtBairro.Locked = True txtCidade.Locked = True txtEstado.Locked = True txtAnotacoes.Locked = True txtEmail.Locked = True Call HabilitaNavegacao txtNome.BackColor = vbWhite txtRua.BackColor = vbWhite txtDataNascimento.BackColor = vbWhite txtNatural.BackColor = vbWhite txtReligiao.BackColor = vbWhite txtSexo.BackColor = vbWhite txtRG.BackColor = vbWhite txtCPF.BackColor = vbWhite txtProfissao.BackColor = vbWhite txtEmpresa.BackColor = vbWhite txtEmail.BackColor = vbWhite txtDDD.BackColor = vbWhite txtTelefone.BackColor = vbWhite txtCelular.BackColor = vbWhite txtTelefoneComercial.BackColor = vbWhite txtNumero.BackColor = vbWhite txtComplemento.BackColor = vbWhite txtCEP.BackColor = vbWhite txtBairro.BackColor = vbWhite txtCidade.BackColor = vbWhite txtEstado.BackColor = vbWhite txtAnotacoes.BackColor = vbWhite txtEmail.BackColor = vbWhite cmdEdita.Enabled = True cmdInclui.Enabled = True cmdExclui.Enabled = True lblEOF = rsMySQL.EOF lblBOF = rsMySQL.BOFEnd SubPrivate Sub cmdExclui_Click() If rsMySQL.EOF = False And _ rsMySQL.BOF = False And _ cmdFechaConexao.Enabled = True Then If MsgBox("Confirma Exclusão deste Registro ? ", vbYesNo, "Excluir Registros") = vbYes Then On Error Resume Next adoDataConn.BeginTrans rsMySQL.Delete adoDataConn.CommitTrans rsMySQL.MoveNext If rsMySQL.EOF = True Then rsMySQL.MoveLast If rsMySQL.BOF = True Then Call limpaControles MsgBox "Não há dados no Arquivo!", , "Sem Dados !" End If End If End If ElseIf rsMySQL.EOF = True And rsMySQL.BOF = True Then MsgBox "Não há dados no Arquivo!", , "Sem Dados !" End If End SubPrivate Sub cmdEdita_Click() If cmdEdita.Caption = "&Editar" And _ cmdFechaConexao.Enabled = True Then cmdEdita.Caption = "&Cancela" cmdSalva.Enabled = True Call DesabilitaNavegacao cmdInclui.Enabled = False cmdExclui.Enabled = False txtNome.Locked = False txtRua.Locked = False txtDataNascimento.Locked = False txtNatural.Locked = False txtReligiao.Locked = False txtSexo.Locked = False txtRG.Locked = False txtCPF.Locked = False txtProfissao.Locked = False txtEmpresa.Locked = False txtEmail.Locked = False txtDDD.Locked = False txtTelefone.Locked = False txtCelular.Locked = False txtTelefoneComercial.Locked = False txtNumero.Locked = False txtComplemento.Locked = False txtCEP.Locked = False txtBairro.Locked = False txtCidade.Locked = False txtEstado.Locked = False txtAnotacoes.Locked = False txtEmail.Locked = False txtNome.BackColor = vbYellow txtRua.BackColor = vbYellow txtDataNascimento.BackColor = vbYellow txtNatural.BackColor = vbYellow txtReligiao.BackColor = vbYellow txtSexo.BackColor = vbYellow txtRG.BackColor = vbYellow txtCPF.BackColor = vbYellow txtProfissao.BackColor = vbYellow txtEmpresa.BackColor = vbYellow txtEmail.BackColor = vbYellow txtDDD.BackColor = vbYellow txtTelefone.BackColor = vbYellow txtCelular.BackColor = vbYellow txtTelefoneComercial.BackColor = vbYellow txtNumero.BackColor = vbYellow txtComplemento.BackColor = vbYellow txtCEP.BackColor = vbYellow txtBairro.BackColor = vbYellow txtCidade.BackColor = vbYellow txtEstado.BackColor = vbYellow txtAnotacoes.BackColor = vbYellow txtEmail.BackColor = vbYellow txtNome.SetFocus ElseIf cmdEdita.Caption = "&Cancela" Then cmdEdita.Caption = "&Editar" cmdSalva.Enabled = False Call HabilitaNavegacao cmdInclui.Enabled = True cmdExclui.Enabled = True txtNome.Locked = True txtRua.Locked = True txtDataNascimento.Locked = True txtNatural.Locked = True txtReligiao.Locked = True txtSexo.Locked = True txtRG.Locked = True txtCPF.Locked = True txtProfissao.Locked = True txtEmpresa.Locked = True txtEmail.Locked = True txtDDD.Locked = True txtTelefone.Locked = True txtCelular.Locked = True txtTelefoneComercial.Locked = True txtNumero.Locked = True txtComplemento.Locked = True txtCEP.Locked = True txtBairro.Locked = True txtCidade.Locked = True txtEstado.Locked = True txtAnotacoes.Locked = True txtEmail.Locked = True txtNome.BackColor = vbWhite txtRua.BackColor = vbWhite txtDataNascimento.BackColor = vbWhite txtNatural.BackColor = vbWhite txtReligiao.BackColor = vbWhite txtSexo.BackColor = vbWhite txtRG.BackColor = vbWhite txtCPF.BackColor = vbWhite txtProfissao.BackColor = vbWhite txtEmpresa.BackColor = vbWhite txtEmail.BackColor = vbWhite txtDDD.BackColor = vbWhite txtTelefone.BackColor = vbWhite txtCelular.BackColor = vbWhite txtTelefoneComercial.BackColor = vbWhite txtNumero.BackColor = vbWhite txtComplemento.BackColor = vbWhite txtCEP.BackColor = vbWhite txtBairro.BackColor = vbWhite txtCidade.BackColor = vbWhite txtEstado.BackColor = vbWhite txtAnotacoes.BackColor = vbWhite txtEmail.BackColor = vbWhite If cmdFechaConexao.Enabled = True Then Call CarregaRegistros End If End IfEnd SubPrivate Sub cmdSair_Click() If cmdFechaConexao.Enabled = True Then Call cmdFechaConexao_Click End If Unload Me EndEnd Sub'ao pressionar a tecla enter aciona o tabPrivate Sub txtcodigo_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then SendKeys "{TAB}" End IfEnd Sub'ao pressionar a tecla enter aciona o tabPrivate Sub txtNome_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then SendKeys "{TAB}" End IfEnd Sub'ao pressionar a tecla enter aciona o tabPrivate Sub txtEndereco_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then SendKeys "{TAB}" End IfEnd Sub'ao pressionar a tecla enter aciona o tabPrivate Sub txtnascimento_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then SendKeys "{TAB}" End IfEnd Sub
mas onde está o problema??você tem certeza de que a query retorna mais de uma linha?
mas onde está o problema??você tem certeza de que a query retorna mais de uma linha?
Também não sei o que acontece apenas que quando se tem mais de uma tabela no select ou utilizo uma combo pegando o campo de outra tabela eu não consigo navegar entre os campos e quando eu tento deletar, inserir algum registro ele também exibe um erro dizendo que a informação da coluna da chave é insuficiente para realizar a operação.E quando carrego o banco sem a combo carregando os campos de uma tabela apenas exibindo o registro atual na propriedade text consigo navegar entre os campos porém ainda assim não consigo realizar as operações de inclusão, exclusão...
Cara, tenta assim:
Public Sub CarregaCidade() dim rsCidades as new adodb.recordset rsCidades.Open "SELECT cidade FROM tb_cidades", adoDataConn, adOpenDynamic, adLockOptimistic while not rsCidades.eof cboCidade.additem rsCidades("cidades") rsCidades.movenext wend set rsCidades = nothingEnd Sub
Sempre que precisar carregar a combo de cidade chama essa rotina.
O problema que está ocorrendo é que lá no form_load note que você carrega somente as cidades utilizadas na outra tabela por isso que não aparecem todos os registros.
>
Cara, tenta assim:
Public Sub CarregaCidade() dim rsCidades as new adodb.recordset rsCidades.Open "SELECT cidade FROM tb_cidades", adoDataConn, adOpenDynamic, adLockOptimistic while not rsCidades.eof cboCidade.additem rsCidades("cidades") rsCidades.movenext wend set rsCidades = nothingEnd SubSempre que precisar carregar a combo de cidade chama essa rotina.O problema que está ocorrendo é que lá no form_load note que você carrega somente as cidades utilizadas na outra tabela por isso que não aparecem todos os registros.
Muito Obrigado Valew deu certo.Porém não consigo incluir um novo registro excluir ou atualizar por exemplo na hora de incluir um novo registro na tabela alunos, como irei fazer para que a cidade que já está pré-cadastrada na tabela cidades fique vinculada a este registro.E na hora de excluir o registro ele exclua somente o registro da tabela alunos mantendo a tabela cidade inalterada.E outra coisa caso eu esteja inserindo um cadastro e a cidade não estiver cadastrada, será que existe a possibilidade de tem um botão ou um item na combo que chame o form de cadastro de cidades e ao finalizar o cadastro da cidade ele atualize a combo com a nova cidade inclusa.Será que a forma com que eu esteja carregando os campos e realizando os metodos de incluir, editar, excluir via ADO não sejam recomendaveis. será que realizar estas operações via mysql torne as melhores. porém como realizar via mysql? muda a forma de carregar os campos, salvar, editar, excluir? ainda não sei como proceder em relação a isto.Obrigado pela ajuda
Na hora de excluir um registro da tabela alunos a tabela de cidades não será alterada, a não quer você também execute com comando DELETE para ela.
Para junto com o nome da cidade salvar o código dela, você pode utilizar a propriedade itemdata que serve para isso:
while not rsCidades.eof cboCidade.additem rsCidades("cidades") cboCidade.itemdata(cbocidade.newindex) = rsCidades("codigo") rsCidades.movenextwend
E na hora de salvar você verifica qual o código da cidade selecionada:
codigo = cboCidade.itemdata(cboCidade.ListIndex)
Já quanto ao modo de interagir com o banco de dados o que você pode é usar só SQL tanto para selecionar, incluir, alterar e apagar registros.
Dá uma conferida nessa série de artigos:
http://www.imasters.com.br/artigo/2940/vis..._consultas_sql/
>
Na hora de excluir um registro da tabela alunos a tabela de cidades não será alterada, a não quer você também execute com comando DELETE para ela.Para junto com o nome da cidade salvar o código dela, você pode utilizar a propriedade itemdata que serve para isso:
while not rsCidades.eof cboCidade.additem rsCidades("cidades") cboCidade.itemdata(cbocidade.newindex) = rsCidades("codigo") rsCidades.movenextwendE na hora de salvar você verifica qual o código da cidade selecionada:codigo = cboCidade.itemdata(cboCidade.ListIndex)Já quanto ao modo de interagir com o banco de dados o que você pode é usar só SQL tanto para selecionar, incluir, alterar e apagar registros.Dá uma conferida nessa série de artigos:http://www.imasters.com.br/artigo/2940/vis..._consultas_sql/
Obrigado Luiz sem palavras ai pra te agradecer pela ajuda valew mesmoFlavioJr
Estava tentando arrumar o código aqui colocando em módulos só que não estou conseguindo navegar entre os registros da tabela.
O que acontece é que não aparece os novos registros no form mais o rs.movenext , last, previous, first funcionam
Option Explicit Public cn As ADODB.Connection Public rsMySQL As ADODB.Recordset Public SQL As String Public ConectaMySQL As StringPublic Sub DBAtivo() Set cn = New ADODB.Connection ' Set rsMySQL = New ADODB.Recordset Set cn = CreateObject("ADODB.Connection") ConectaMySQL = "Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=sunrise_db;User=root;Password=flaviojr;Option=3;" cn.CursorLocation = adUseClient cn.Open ConectaMySQL Set rsMySQL = New ADODB.Recordset rsMySQL.CursorType = adOpenStatic rsMySQL.CursorLocation = adUseClient rsMySQL.LockType = adLockPessimistic rsMySQL.ActiveConnection = cn ' rsMySQL.Open End Sub Public Sub DBFechar() Set cn = Nothing If rsMySQL Is Nothing Then Else rsMySQL.Close Set rsMySQL = Nothing End Sub
e o código que é carregado no form
Private Sub Form_Load()Call DBAtivoSQL = "SELECT * FROM tb_alunos"Set rsMySQL = cn.Execute(SQL)txtNome.Text = rsMySQL!NomeEnd Sub
e no botão de navegação movenext
If Not rsMySQL.EOF Then rsMySQL.MoveNext If rsMySQL.EOF And rsMySQL.RecordCount > 0 Then Beep rsMySQL.MoveLast MsgBox "Esté é o ultimo registro.", _ vbInformation, "Ultimo Registro" End If
Sempre que você alterar a tabela carregue novamente o recordset.Deve ser isso.
Sempre que você alterar a tabela carregue novamente o recordset.Deve ser isso.
Valew pela ajuda Mais o pior é que ainda não deu certo, o estranho é que quando está toda a conexão no form funciona.
Pra resolver deixei apenas a conexão com o banco no módulo e no form joguei a recordsetObrigado por toda a ajuda Flavio Jr.
Mostra como você está fazendo.
Olá Luiz, gostaria de saber qual a melhor forma de connecção ao mysql.Cheguei a criar uma classe para iss chamada RepositorioMySqlO que eu quero é ter um único objeto de conexão ao mysql dentro de minha aplicaçãoa classe é o seguinte:Option ExplicitPublic Enum StatusConexao adStateClosed = 0 'Conexão esta fechada adStateOpen = 1 'Conexão esta aberta adStateConnecting = 2 'Conexão em andamento adStateExecuting = 4 'Executando instrução SQL adStateFetching = 8 'Retornando dadosEnd Enum'Private vNomeDSN As String = App.Path & ".\Reports\SISTEMA.dsn"'local variable(s) to hold property value(s)Private vDBmyCon As New ADODB.ConnectionPrivate vDBmyCmd As New ADODB.CommandPrivate vDBmyRS As New ADODB.Recordset'Private mvarvDBmySql As StringPrivate mvarvDBConector As String 'local copyPrivate mvarvDBServidor As String 'local copyPrivate mvarvDBNomeINIConector As String 'local copyPrivate mvarvDBPorta As String 'local copyPrivate mvarvDBUser As String 'local copyPrivate mvarvDBPassword As String 'local copyPrivate mvarvDBBanco As String 'local copyPrivate mvarvDBStatusConexao As Integer 'local copyPrivate mvarvDBStringConexao As String 'local copyPrivate vDBNomeDsn As StringPrivate vDBNomeINI As StringPublic Property Let vDBStringConexao(ByVal vData As String)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.vDBStringConexao = 5 mvarvDBStringConexao = vDataEnd PropertyPublic Property Get vDBStringConexao() As String'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.vDBStringConexao vDBStringConexao = mvarvDBStringConexaoEnd PropertyPublic Property Let vDBStatusConexao(ByVal vData As Integer)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.vDBStatusConexao = 5 mvarvDBStatusConexao = vDataEnd PropertyPublic Property Get vDBStatusConexao() As Integer'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.vDBStatusConexao' Permite conhecer o modo do estado da conexão do banco de dados vDBStatusConexao = mvarvDBStatusConexaoEnd PropertyPublic Property Let vDBBanco(ByVal vData As String)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.vDBBanco = 5 mvarvDBBanco = vDataEnd PropertyPublic Property Get vDBBanco() As String'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.vDBBanco vDBBanco = mvarvDBBancoEnd PropertyPublic Property Let vDBPassword(ByVal vData As String)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.vDBPassword = 5 mvarvDBPassword = vDataEnd PropertyPublic Property Get vDBPassword() As String'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.vDBPassword vDBPassword = mvarvDBPasswordEnd PropertyPublic Property Let vDBUser(ByVal vData As String)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.vDBUser = 5 mvarvDBUser = vDataEnd PropertyPublic Property Get vDBUser() As String'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.vDBUser vDBUser = mvarvDBUserEnd PropertyPublic Property Let vDBPorta(ByVal vData As String)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.vDBPorta = 5 mvarvDBPorta = vDataEnd PropertyPublic Property Get vDBPorta() As String'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.vDBPorta vDBPorta = mvarvDBPortaEnd PropertyPublic Property Let vDBNomeINIConector(ByVal vData As String)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.vDBNomeINIConector = 5 mvarvDBNomeINIConector = vDataEnd PropertyPublic Property Get vDBNomeINIConector() As String'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.vDBNomeINIConector vDBNomeINIConector = mvarvDBNomeINIConectorEnd PropertyPublic Property Let vDBServidor(ByVal vData As String)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.vDBServidor = 5 mvarvDBServidor = vDataEnd PropertyPublic Property Get vDBServidor() As String'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.vDBServidor vDBServidor = mvarvDBServidorEnd PropertyPublic Property Let vDBConector(ByVal vData As String)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.vDBConector = 5 mvarvDBConector = vDataEnd Property'---------------------------------------------------------------------------------------' Procedure : vDBConector' DateTime : 14/3/2007 21:30' Author : KLAYTON' Purpose :'---------------------------------------------------------------------------------------'Public Property Get vDBConector() As String'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.vDBConector On Error GoTo vDBConector_Error vDBConector = mvarvDBConector On Error GoTo 0 Exit PropertyvDBConector_Error: MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure vDBConector of Módulo de classe RepositorioMySql"End PropertyPublic Function CriarRepositorio()Dim vConector As StringDim vServidor As StringDim vPorta As StringDim vUser As StringDim vPassword As StringDim vBanco As String '//VERIFICA SE O ARQUIVO DBConnection.ini If Len(Dir$(vDBNomeINI)) = 0 Then MsgBox "Arquivo de conexão ao Banco de Dados não existe! Gere este arquivo com o Utilitário DBConnection localizado na pasta do sistema. Ou se preferir entre em contato com o suporte: Klayton de Oliveira. Fone: 81-9216.5011", vbExclamation + vbOKOnly End Else '// Inicializa as variáveis vConector = DeCriptSenha(LeEntradaIni("ODBC", "DRIVER", "", vDBNomeINI)) vServidor = DeCriptSenha(LeEntradaIni("ODBC", "SERVIDOR", "", vDBNomeINI)) vPorta = DeCriptSenha(LeEntradaIni("ODBC", "PORT", "", vDBNomeINI)) ' DeCriptSenha(GetSetting("Tools", "Options", "My_Port", "CHAVE NÃO EXISTE")) vUser = DeCriptSenha(LeEntradaIni("ODBC", "UID", "", vDBNomeINI)) ' DeCriptSenha(GetSetting("Tools", "Options", "My_User", "CHAVE NÃO EXISTE")) vPassword = DeCriptSenha(LeEntradaIni("ODBC", "PWD", "", vDBNomeINI)) 'DeCriptSenha(GetSetting("Tools", "Options", "My_Password", "CHAVE NÃO EXISTE")) vBanco = DeCriptSenha(LeEntradaIni("ODBC", "DATABASE", "", vDBNomeINI)) ' DeCriptSenha(GetSetting("Tools", "Options", "My_Database", "CHAVE NÃO EXISTE")) If FU_TestaConexao(vConector, vServidor, vPorta, vUser, vPassword, vBanco) = False Then MsgBox "Não foi possível se conectar ao Servidor. Refaça a conexão." End Else vDBConector = vConector vDBServidor = vServidor vDBPorta = vPorta vDBUser = vUser vDBPassword = vPassword vDBBanco = vBanco vDBStringConexao = FU_CriaStringConexao(vConector, vServidor, vPorta, vUser, vPassword, vBanco) 'Set DB = CreateObject(RepositorioMySql) 'MySqlOpen ' Dim NomeBAT As String, NomeSQL As String ' NomeBAT = "c:\mysql.bat" ' NomeSQL = "c:\" & App.EXEName & Format(Date, "ddmmyy") & Format(Time, "hh") & ".sql" ' If Len(Dir$(NomeSQL)) = 0 Then ' Open NomeBAT For Output As #1 ' Print #1, "cd.." ' Print #1, "cd.." ' Print #1, "cd.." ' Print #1, "cd.." ' Print #1, "cd.." ' Print #1, "cd.." ' Print #1, "mysqldump --host=" & vDBServidor & " --user=" & vDBUser & " --port=" & vDBPorta & " --password=" & vDBPassword & " --opt scg > " & NomeSQL ' 'Print #1, "pause" ' Close #1 ' ' If Len(Dir$(NomeBAT)) > 0 Then ' Dim iTask As Long, Ret As Long, pHandle As Long ' 'BACKUP.Show ' iTask = Shell(Chr(34) & NomeBAT & Chr(34), vbHide) ' pHandle = OpenProcess(SYNCHRONIZE, False, iTask) ' Ret = WaitForSingleObject(pHandle, INFINITE) ' Ret = CloseHandle(pHandle) ' 'exclui o arquivo mysql.bat ' Call Kill("c:\mysql.bat") ' 'Unload BACKUP ' End If ' End If 'MsgBox " /c mysqldump --host=" & vServidor & " --user=" & vUser & " --port=" & vPorta & " --password=" & vPassword & " --opt scg > " & Chr(34) & App.Path & "\" & Date & "_" & Time & ".sql" & Chr(34) 'Shell Environ$("COMSPEC") & " /c mysqldump --host=" & vServidor & " --user=" & vUser & " --port=" & vPorta & " --password=" & vPassword & " --opt scg > " & Chr(34) & App.Path & "\" & Format(Date, "dd-mm-yyyy") & "_" & Time & ".sql" & Chr(34) 'Call Shell("mysqldump --host=" & vServidor & " --user=" & vUser & " --port=" & vPorta & " --password=" & vPassword & " --opt scg > " & Chr(34) & App.Path & "\" & Format(Date, "dd-mm-yyyy") & "_" & Time & ".sql" & Chr(34) & " pause", vbNormalFocus) End If End If' Matar as classes não utilizadas' Set Crypt = Nothing End FunctionPublic Function OpenDB() On Error GoTo OpenDB_Error vDBmyCon.Open vDBStringConexao ' StringConnection '"driver={MySQL ODBC 3.51 Driver};server=localhost;database=cat;uid=root;pwd=kofb@123;port=3307;option=2;option=35;option=16834;option=18475" vDBStatusConexao = vDBmyCon.State On Error GoTo 0 Exit FunctionOpenDB_Error: MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure OpenDB of Módulo de classe RepositorioMySql" End FunctionPublic Function CloseDB() On Error GoTo CloseDB_Error If vDBmyCon.State = ADODB.adStateOpen Then vDBmyCon.Close Set vDBmyCon = Nothing End If vDBStatusConexao = vDBmyCon.State On Error GoTo 0 Exit FunctionCloseDB_Error: MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure CloseDB of Módulo de classe RepositorioMySql" End FunctionPublic Function Insert(ByVal Sql As String) As Boolean If vDBStatusConexao = StatusConexao.adStateOpen Then Call ExecuteSQL(Sql) End IfEnd FunctionPublic Function Delete(ByVal Sql As String) As Boolean On Error GoTo Delete_Error If vDBStatusConexao = StatusConexao.adStateOpen Then Call ExecuteSQL(Sql) End If On Error GoTo 0 Exit FunctionDelete_Error: MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Delete of Módulo de classe RepositorioMySql"End FunctionPublic Function Edit(ByVal Sql As String) As Boolean If vDBStatusConexao = StatusConexao.adStateOpen Then Call ExecuteSQL(Sql) End IfEnd FunctionPublic Function Update(ByVal Sql As String) As Boolean If vDBStatusConexao = StatusConexao.adStateOpen Then Call ExecuteSQL(Sql) End IfEnd FunctionPublic Sub ExecuteSQL(Sql As String) On Error GoTo Error_ExecuteSQL With vDBmyCmd Set .ActiveConnection = vDBmyCon .CommandType = adCmdText .CommandText = Sql End With With vDBmyRS .LockType = adLockPessimistic .CursorType = adOpenKeyset .CursorLocation = adUseClient .Open vDBmyCmd End With 'myRS.MoveFirst 'MostraNumeroRegistro 'Mostra_dados 'vDBmyRS.Close Set vDBmyRS = Nothing Set vDBmyCon = Nothing On Error GoTo 0 Exit Sub Error_ExecuteSQL: MsgBox Err.Number & vbCrLf & Err.Description, vbExclamation, "Error_ExecuteSQL" 'NomeAdodc.ConnectionString = "Provider=MSDASQL.1;Password='';Persist Security Info=True;User ID=root;Data Source=" & XNOME_BANCO & ";option=35" 'NomeAdodc.RecordSource = SQL 'NomeAdodc.Refresh 'nomeAdodc.Recordset.Close End SubPublic Function CriarTB(Sql As String) As ADODB.RecordsetDim rs As New ADODB.Recordset'define os parâmetros do recordset On Error GoTo CriarTB_Errorrs.CursorType = adOpenStaticrs.CursorLocation = adUseClientrs.LockType = adLockOptimisticrs.ActiveConnection = vDBmyCon' executa a consuta e retorna um recordsetrs.Open SqlSet CriarTB = rs On Error GoTo 0 Exit FunctionCriarTB_Error: MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure CriarTB of Módulo de classe RepositorioMySql"End FunctionPublic Function FU_TestaConexao(ByVal Driver As String, ByVal Server As String, ByVal Port As String, ByVal User As String, ByVal Password As String, ByVal DB As String) As BooleanDim myCon As New ADODB.ConnectionDim StringDeConexao As String StringDeConexao = FU_CriaStringConexao(Driver, Server, Port, User, Password, DB) On Error GoTo Error 'Debug.Print StringDeConexao myCon.Open StringDeConexao ' & "klayton de olivceira ferreira barbosa" If myCon.State = 1 Then FU_TestaConexao = True 'vDBStringConexao = StringDeConexao ElseIf myCon.State = 0 Then FU_TestaConexao = False 'vDBStringConexao = "" 'StringDeConexao End If myCon.Close Set myCon = NothingError: If Not Err.Number = 0 Then MsgBox Err.Number & vbCrLf & Err.Description, vbExclamation, "Erro em [FU_TestaConexao]" End If 'NomeAdodc.ConnectionString = "Provider=MSDASQL.1;Password='';Persist Security Info=True;User ID=root;Data Source=" & XNOME_BANCO & ";option=35" 'NomeAdodc.RecordSource = SQL 'NomeAdodc.Refresh 'nomeAdodc.Recordset.Close End FunctionPublic Function FU_CriaStringConexao(ByVal Driver As String, ByVal Server As String, ByVal Port As String, ByVal User As String, ByVal Password As String, ByVal DB As String) As String FU_CriaStringConexao = "driver={" & Driver & "};server=" & Server & ";database=" & DB & ";uid=" & User & ";pwd=" & Password & ";port=" & Port & ";option=35;option=16834;option=18475"End FunctionPublic Function FU_VerificaEstadoDaConexao() As Integer 'FU_VerificaEstadoDaConexao = v 'FU_TestaConexao(vDBConector, vDBServidor, vDBPorta, vDBUser, vDBPassword, vDBBanco) = True ' vDBStatusConexao = vDBmyCon.State ' FU_VerificaEstadoDaConexao = vDBmyCon.State' Select Case vDBmyCon.State' Case adStateClosed' vDBStatusConexao = "Conexão esta fechada"''' Case adStateOpen' vDBStatusConexao = "Conexão esta aberta"''' Case adStateConnecting' vDBStatusConexao = "Conexão em andamento"''' Case adStateExecuting' vDBStatusConexao = "Executando instrução SQL"'' Case adStateFetching' vDBStatusConexao = "Retornando dados"'' Case Else' vDBStatusConexao = "Estado desconhecido."'' End SelectEnd FunctionPrivate Sub Class_Initialize() vDBNomeDsn = App.Path & ".\Reports\SISTEMA.dsn" vDBNomeINI = App.Path & "\DBConnection" & App.EXEName & ".ini" CriarRepositorioEnd SubPrivate Sub Class_Terminate() DBCloseEnd SubPublic Sub Create_Dsn() Dim registros As Integer Open vDBNomeDsn For Output As #1 Print #1, "[ODBC]" Print #1, "DRIVER=" & vDBConector Print #1, "SERVIDOR=" & vDBServidor Print #1, "PORT=" & vDBPorta Print #1, "UID=" & vDBUser Print #1, "PWD=" & vDBPassword Print #1, "DATABASE=" & vDBBanco Close #1 'MsgBox "Foi criado o Arquivo: " & nome_dsn End Sub
Eu utlizo conexao via ODBC configuro o driver myodbc 3.51 no painel de controle e crio a conexão em um modulo onde crio o OBjeto de conexão e abro os Objetos recordsets nos respectivos forms.No modulo:Option Explicit Global objCN As ADODB.Connection Global objrs As ADODB.Recordset Global objStream As ADODB.Stream Global ConectaMySQL As String Global sSql As String Public Sub abrirConexao() Set objCN = New ADODB.Connection ConectaMySQL = "Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=MeuBanco;User=root;Password=flaviojr;Option=1 + 2 + 8 + 32 + 2048 + 16384;" objCN.CursorLocation = adUseClient objCN.Open ConectaMySQL End Sub++++++++++++++++++++++++++++++++++++++++++++++++++++no form deixo o recordsetabrirConexaoSet objrs = New ADODB.Recordset objrs.CursorLocation = adUseClient objrs.CursorType = adOpenStatic objrs.LockType = adLockOptimistic objrs.ActiveConnection = objCN Set objrs = objCN.Execute("SELECT * FROM tabela ")+++++++++++++++++++++++++++++++++++++++++Até mais
Mostra como você está fazendo.