Herramientas Informaticas

Etiqueta: MySQL

Creando texto para vista PHP8 en base a la tabla usando Visual Basic 2022

Ahora solo queda hacer la función para generar automáticamente el código HTML/PHP para la vista del catalogo en base a la nueva tabla.

La lógica es igual solo que es otro texto

Insertamos el siguiente código

'IMPORTAMOS LAS LIBRERIAS NECESARIAS PARA LA CONEXIÓN A MYSQL/MARIADB
Imports MySqlConnector.MySqlConnection

'EMPIEZA EL MODULO
Module crearVista

    ' CON PUBLIC SUB CREAMOS PROCEDIMIENTOS
    Public Function generarVista() As String

        ' VARIABLES PARA LA CONEXIÓN
        Dim strServidor As String
        Dim strBaseDeDatos As String
        Dim strUsuario As String
        Dim strContra As String

        'Variables de uso
        Dim contador As Integer
        Dim strEncabezadosTabla As String
        Dim strCampos As String
        Dim strControlesNuevos As String
        Dim strControlesEditar As String
        Dim strEditarJS As String
        Dim strBloquear As String
        Dim strEditarTraeDatos As String
        Dim strDatos As String
        Dim strLLavePrimaria As String
        Dim strVista As String
        Dim strSegundoCampo As String

        contador = 0
        strEncabezadosTabla = ""
        strCampos = ""
        strControlesNuevos = ""
        strEditarJS = ""
        strDatos = ""

        'OBTENEMOS LOS DATOS DE CONFIGURACIÖN DEL REGISTRO DE WINDOWS PREVIAMENTE GUARDADAS
        If Not My.Computer.Registry.GetValue("HKEY_CURRENT_USER\CREADORMVCPHP", "servidor", Nothing) Is Nothing Then
            strServidor = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\CREADORMVCPHP", "servidor", Nothing).ToString()
            strBaseDeDatos = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\CREADORMVCPHP", "baseDeDatos", Nothing).ToString()
            strUsuario = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\CREADORMVCPHP", "usuario", Nothing).ToString()
            strContra = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\CREADORMVCPHP", "contra", Nothing).ToString()
        Else

            MsgBox("No se han capturado la conexión a la base de datos")
            Exit Function


        End If


        ' METEMOS LA CADENA DE CONEXIÓN EN UNA VARIABLE
        Dim cadenaConexion = "Server=" & strServidor & ";User ID=" & strUsuario & ";Password=" & strContra & ";Database=" & strBaseDeDatos

        ' CREAMOS LA CONEXIÓN CON LA CADENA DE CONEXIÓN
        Dim connection = New MySqlConnector.MySqlConnection(cadenaConexion)

        Try


            connection.Open()
            Dim comando = New MySqlConnector.MySqlCommand("delete from clases where clase= 'controladores/" & frmCreaCatalogo.txtTabla.Text & ".controlador.php'", connection)
            Dim resultado = comando.ExecuteReader()
            comando = Nothing
            resultado = Nothing
            connection.Close()



            connection.Open()
            comando = New MySqlConnector.MySqlCommand("delete from clases where clase= 'modelos/" & frmCreaCatalogo.txtTabla.Text & ".modelo.php'", connection)
            resultado = comando.ExecuteReader()
            comando = Nothing
            resultado = Nothing
            connection.Close()

            connection.Open()
            comando = New MySqlConnector.MySqlCommand("insert into clases(clase) values('controladores/" & frmCreaCatalogo.txtTabla.Text & ".controlador.php')", connection)
            resultado = comando.ExecuteReader()
            comando = Nothing
            resultado = Nothing
            connection.Close()

            connection.Open()
            comando = New MySqlConnector.MySqlCommand("insert into clases(clase) values( 'modelos/" & frmCreaCatalogo.txtTabla.Text & ".modelo.php')", connection)
            resultado = comando.ExecuteReader()
            comando = Nothing
            resultado = Nothing
            connection.Close()

            ' SI SE ABRE LA CONEXIÓN MANDAMOS MENSAJE
            connection.Open()




            comando = New MySqlConnector.MySqlCommand("SHOW KEYS FROM  " & frmCreaCatalogo.txtTabla.Text & " WHERE Key_name = 'PRIMARY'", connection)

            resultado = comando.ExecuteReader

            resultado.Read()


            'ASIGNAMOS EL CAMPO LLAVE

            strLLavePrimaria = resultado.GetString("Column_name")


            'OBTENEMOS LOS CAMPOS DE LA TABLA
            connection.Close()
            connection.Open()
            comando = Nothing
            comando = New MySqlConnector.MySqlCommand("describe  " & frmCreaCatalogo.txtTabla.Text & "", connection)
            resultado = Nothing
            resultado = comando.ExecuteReader



            contador = 0


            While (resultado.Read)
                strEncabezadosTabla &= "<th>" & utilerias.strPrimeraMayuscula(resultado("Field")) & "</th>" & vbCrLf

                strCampos &= "<td>'.$value[""" & resultado("Field") & """].'</td>" & vbCrLf

                If contador > 0 Then

                    strControlesNuevos &= "" & "            <!-- ENTRADA PARA " & UCase(resultado("Field")) & " --> " & vbCrLf
                    strControlesNuevos &= "" & " " & vbCrLf
                    strControlesNuevos &= "" & "            <div class=""form-group""> " & vbCrLf
                    strControlesNuevos &= "" & " " & vbCrLf
                    strControlesNuevos &= "" & "              <div class=""input-group""> " & vbCrLf
                    strControlesNuevos &= "" & " " & vbCrLf
                    strControlesNuevos &= "" & "                <span class=""input-group-addon"">" & utilerias.strPrimeraMayuscula(resultado("Field")) & ": </span>  " & vbCrLf
                    strControlesNuevos &= "" & " " & vbCrLf
                    strControlesNuevos &= "" & "                <input type=""text"" class=""form-control input-lg"" name=""nuevo" & utilerias.strPrimeraMayuscula(resultado("Field")) & """ placeholder=""Ingresar " & utilerias.strPrimeraMayuscula(resultado("Field")) & """ required> " & vbCrLf
                    strControlesNuevos &= "" & " " & vbCrLf
                    strControlesNuevos &= "" & "              </div> " & vbCrLf
                    strControlesNuevos &= "" & " " & vbCrLf
                    strControlesNuevos &= "" & "            </div> " & vbCrLf

                    strEditarJS &= "" & "            $(""#editarDescripcion"").val(respuesta[""descripcion""]);" & vbCrLf

                End If


                If resultado("Key") = "PRI" Then
                    strBloquear = "readonly"
                Else
                    strBloquear = ""
                End If



                strControlesEditar &= "" & "            <!-- ENTRADA PARA " & UCase(resultado("Field")) & " --> " & vbCrLf
                strControlesEditar &= "" & " " & vbCrLf
                strControlesEditar &= "" & "            <div class=""form-group""> " & vbCrLf
                strControlesEditar &= "" & " " & vbCrLf
                strControlesEditar &= "" & "              <div class=""input-group""> " & vbCrLf
                strControlesEditar &= "" & " " & vbCrLf
                strControlesEditar &= "" & "                <span class=""input-group-addon"">" & utilerias.strPrimeraMayuscula(resultado("Field")) & ": </span>  " & vbCrLf
                strControlesEditar &= "" & " " & vbCrLf
                strControlesEditar &= "" & "                <input " & strBloquear & "  type=""text"" class=""form-control input-lg"" id=""editar" & utilerias.strPrimeraMayuscula(resultado("Field")) & """ name=""editar" & utilerias.strPrimeraMayuscula(resultado("Field")) & """ placeholder=""Ingresar " & utilerias.strPrimeraMayuscula(resultado("Field")) & """ required> " & vbCrLf
                strControlesEditar &= "" & " " & vbCrLf
                strControlesEditar &= "" & "              </div> " & vbCrLf
                strControlesEditar &= "" & " " & vbCrLf
                strControlesEditar &= "" & "            </div> " & vbCrLf

                strEditarTraeDatos &= "" & "            $(""#editar" & utilerias.strPrimeraMayuscula(resultado("Field")) & """).val(respuesta[""" & resultado("Field") & """]); " & vbCrLf

                contador = contador + 1

            End While


            strControlesEditar &= "" & " <input type=""hidden"" id=""editar" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & """  name = ""editar" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & """ > " & vbCrLf
            strEncabezadosTabla &= "<th>Acciones</th>"
            strCampos &= "<td> " & vbCrLf
            strCampos &= "<div class = ""btn-group""> " & vbCrLf



            strCampos &= "                    <button class= ""btn btn-warning btnEditar" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & """ id" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & " = ""'.$value[""id""].'"" data-toggle = ""modal"" data-target = ""#modalEditar" & Trim(utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text)) & """> <i class = ""fa fa-pencil""> </i> </button> " & vbCrLf

            strCampos &= "<button class = ""btn btn-danger btnEliminar" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & """ id" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & "= ""'.$value[""id""].'""><i class= ""fa fa-times""></i></button>" & vbCrLf

            strCampos &= "</div>" & vbCrLf

            strCampos &= "</td> " & vbCrLf

            strVista &= "" & "<?php" & vbCrLf
            strVista &= "" & vbCrLf
            strVista &= "" & "if(""off"" == ""offf""){" & vbCrLf
            strVista &= "" & vbCrLf
            strVista &= "" & "  echo '<script>" & vbCrLf
            strVista &= "" & vbCrLf
            strVista &= "" & "    window.location = ""inicio""; " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "  </script>'; " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "  return; " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "} " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "?> " & vbCrLf
            strVista &= "" & "<div class=""content-wrapper"">" & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "  <section class=""content-header"">" & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "    <h1> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "      Administrar <?php echo  mb_strtolower(preg_replace('/(?<=\\w)(\\p{Lu})/u', ' $1', ' " & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & " ')); ?> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "    </h1> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "    <ol class=""breadcrumb""> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "      <li><a href=""inicio""><i class=""fa fa-dashboard""></i> Inicio</a></li> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "      <li class=""active"">Administrar <?php echo  mb_strtolower(preg_replace('/(?<=\\w)(\\p{Lu})/u', ' $1', '" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & " ')); ?></li> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "    </ol> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "  </section> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "  <section class=""content""> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "    <div class=""box""> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "      <div class=""box-header With-border""> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        <button class=""btn btn-primary"" data-toggle=""modal"" data-target=""#modalAgregar" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & """> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "          Agregar <?php echo  mb_strtolower(preg_replace('/(?<=\\w)(\\p{Lu})/u', ' $1', '" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & " ')); ?> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        </button> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "      </div> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "      <div class=""box-body""> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "       <table class=""table table-bordered table-striped dt-responsive tablas"" width=""100%""> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        <thead> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "         <tr> " & vbCrLf
            strVista &= "" & " " & strEncabezadosTabla
            strVista &= "" & "         </tr>  " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        </thead> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        <tbody> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        <?php " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        $item = null; " & vbCrLf
            strVista &= "" & "        $valor = null; " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        $" & frmCreaCatalogo.txtTabla.Text & "= Controlador" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & "::ctrMostrar($item, $valor); " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "       foreach ($" & frmCreaCatalogo.txtTabla.Text & " as $key => $value){ " & vbCrLf
            strVista &= "" & " " & vbCrLf



            strVista &= "" & "          echo ' <tr> " & vbCrLf

            strVista &= "" & strCampos & vbCrLf

            strVista &= "" & " " & vbCrLf
            strVista &= "" & "                </tr>'; " & vbCrLf
            strVista &= "" & "        } " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        ?>  " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        </tbody> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "       </table> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "      </div> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "    </div> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "  </section> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "</div> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "<!--===================================== " & vbCrLf
            strVista &= "" & "MODAL <?php echo  mb_strtolower(preg_replace('/(?<=\\w)(\\p{Lu})/u', ' $1', ' " & (frmCreaCatalogo.txtTabla.Text) & " ')); ?> " & vbCrLf
            strVista &= "" & " ======================================--> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "<div id=""modalAgregar" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & """ class=""modal fade"" role=""dialog""> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "  <div class=""modal-dialog""> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "    <div class=""modal-content""> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "      <form role=""form"" method=""post"" enctype=""multipart/form-data""> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        <!--===================================== " & vbCrLf
            strVista &= "" & "        CABEZA DEL MODAL " & vbCrLf
            strVista &= "" & "        ======================================--> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        <div class=""modal-header"" style=""background:#3c8dbc; color:white"" > " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "          <button type=""button"" class=""close"" data-dismiss=""modal"">&times;</button> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "          <h4 class=""modal-title"">Agregar <?php echo  mb_strtolower(preg_replace('/(?<=\\w)(\\p{Lu})/u', ' $1', ' " & (frmCreaCatalogo.txtTabla.Text) & " ')); ?> </h4> " & vbCrLf
            strVista &= "" & " " & vbCrLf

            strVista &= "" & "        </div> " & vbCrLf

            strVista &= "" & "        <!--===================================== " & vbCrLf
            strVista &= "" & "        CUERPO DEL MODAL " & vbCrLf
            strVista &= "" & "        ======================================--> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        <div class=""modal-body""> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "          <div class=""box-body""> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "            <!-- ENTRADA PARA DESCRIPCION --> " & vbCrLf

            strVista &= "" & " " & strControlesNuevos & vbCrLf


            strVista &= "" & " " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "          </div> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        </div> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        <!--===================================== " & vbCrLf
            strVista &= "" & "        PIE DEL MODAL " & vbCrLf
            strVista &= "" & "        ====================================== --> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        <div class=""modal-footer""> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "          <button type=""button"" class=""btn btn-Default pull-left"" data-dismiss=""modal"">Salir</button> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "          <button type=""submit"" class=""btn btn-primary"">Guardar</button> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        </div> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        <?php " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "           $crear = new Controlador" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & "(); " & vbCrLf
            strVista &= "" & "           $crear ->ctrIngresar(); " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        ?> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "      </form> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "    </div> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "  </div> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "</div> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "<!--===================================== " & vbCrLf
            strVista &= "" & "MODAL EDITAR USUARIO " & vbCrLf
            strVista &= "" & " ======================================--> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "<div id=""modalEditar" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & """ class=""modal fade"" role=""dialog"">" & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "  <div class=""modal-dialog""> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "    <div class=""modal-content""> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "      <form role=""form"" method=""post"" enctype=""multipart/form-data""> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        <!--===================================== " & vbCrLf
            strVista &= "" & "        CABEZA DEL MODAL " & vbCrLf
            strVista &= "" & "        ======================================--> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        <div class=""modal-header"" style=""background:#3c8dbc; color:white"" > " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "          <button type=""button"" class=""close"" data-dismiss=""modal"">&times;</button> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "          <h4 class=""modal-title"">Agregar <?php echo  mb_strtolower(preg_replace('/(?<=\\w)(\\p{Lu})/u', ' $1', ' " & (frmCreaCatalogo.txtTabla.Text) & " ')); ?> </h4> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        </div> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        <!--===================================== " & vbCrLf
            strVista &= "" & "        CUERPO DEL MODAL " & vbCrLf
            strVista &= "" & "        ======================================--> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        <div class=""modal-body""> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "          <div class=""box-body""> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "            <!-- ENTRADA PARA DESCRIPCION --> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & strControlesEditar
            strVista &= "" & " " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "          </div> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        </div> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        <!--===================================== " & vbCrLf
            strVista &= "" & "        PIE DEL MODAL " & vbCrLf
            strVista &= "" & "        ======================================--> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        <div class=""modal-footer""> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "          <button type=""button"" class=""btn btn-Default pull-left"" data-dismiss=""modal"">Salir</button> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "          <button type=""submit"" class=""btn btn-primary"">Modificar</button> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        </div> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "     <?php " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "           $editar = new Controlador" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & "(); " & vbCrLf
            strVista &= "" & "           $editar ->ctrEditar(); " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "        ?>  " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "      </form> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "    </div> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "  </div> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "</div> " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "<?php " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "   $borrar = new Controlador" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & "(); " & vbCrLf
            strVista &= "" & "   $borrar ->ctrBorrar(); " & vbCrLf
            strVista &= "" & " " & vbCrLf
            strVista &= "" & "?>  " & vbCrLf

            'JAVASCRIPT FUNCIONES
            strVista &= "" & "<script type=""text/javascript"">" & vbCrLf

            'ELIMINAR


            strVista &= "" & "/*= == == == == == == == == == == == == == == == == == == == == == ==" & vbCrLf
            strVista &= "" & " ELIMINAR " & UCase(frmCreaCatalogo.txtTabla.Text) & vbCrLf
            strVista &= "" & " == == == == == == == == == == == == == == == == == == == == == == = */" & vbCrLf
            strVista &= "" & "$("".tablas "").on(""click"", "".btnEliminar" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & """, function() {" & vbCrLf

            strVista &= "" & "    var id" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & " = $(this).attr(""id" & frmCreaCatalogo.txtTabla.Text & """);" & vbCrLf

            strVista &= "" & "    swal( {" & vbCrLf
            strVista &= "" & "        title: '¿Está seguro de borrar?'," & vbCrLf
            strVista &= "" & "        text: ""¡Si no lo está puede cancelar la accíón!""," & vbCrLf
            strVista &= "" & "        type: 'warning'," & vbCrLf
            strVista &= "" & "        showCancelButton: true," & vbCrLf
            strVista &= "" & "        confirmButtonColor: '#3085d6'," & vbCrLf
            strVista &= "" & "        cancelButtonColor: '#d33'," & vbCrLf
            strVista &= "" & "        cancelButtonText: 'Cancelar'," & vbCrLf
            strVista &= "" & "       confirmButtonText: 'Si, borrar!'" & vbCrLf
            strVista &= "" & "    }).then(function(result) {" & vbCrLf
            strVista &= "" & "" & vbCrLf
            strVista &= "" & "        if (result.value) {" & vbCrLf
            strVista &= "" & "" & vbCrLf
            strVista &= "" & "            window.location = ""index.php?ruta=" & (frmCreaCatalogo.txtTabla.Text) & "&id" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & "=""+id" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & "+""&borrar" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & "=borrar"";" & vbCrLf
            strVista &= "" & "" & vbCrLf
            strVista &= "" & "        }" & vbCrLf
            strVista &= "" & "" & vbCrLf
            strVista &= "" & "    })" & vbCrLf

            strVista &= "" & "})" & vbCrLf


            'editar

            strVista &= "" & "/* = == == == == == == == == == == == == == == == == == == == == == ==" & vbCrLf
            strVista &= "" & " EDITAR " & vbCrLf
            strVista &= "" & " == == == == == == == == == == == == == == == == == == == == == == = */" & vbCrLf
            strVista &= "" & "$("".tablas "").on(""click"", "".btnEditar" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & """, function() {" & vbCrLf
            strVista &= "" & "" & vbCrLf
            strVista &= "" & "    var id" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & " = $(this).attr(""id" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & """);" & vbCrLf
            strVista &= "" & "  console.log(id" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & ");"
            strVista &= "" & "" & vbCrLf
            strVista &= "" & "" & vbCrLf
            strVista &= "" & "    var datos = new FormData();" & vbCrLf
            strVista &= "" & "    datos.append(""id" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & """, id" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & "); " & vbCrLf
            strVista &= "" & "    datos.append(""buscar" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & """, ""buscar" & utilerias.strPrimeraMayuscula(frmCreaCatalogo.txtTabla.Text) & """);" & vbCrLf
            strVista &= "" & "   " & vbCrLf
            strVista &= "" & "" & vbCrLf
            strVista &= "" & "    $.ajax( {" & vbCrLf
            strVista &= "" & "" & vbCrLf
            strVista &= "" & "        url:""controladores/" & frmCreaCatalogo.txtTabla.Text & ".controlador.php""," & vbCrLf
            strVista &= "" & "        method:""POST""," & vbCrLf
            strVista &= "" & "        data: datos," & vbCrLf
            strVista &= "" & "        cache: false," & vbCrLf
            strVista &= "" & "        contentType: false," & vbCrLf
            strVista &= "" & "        processData: false," & vbCrLf
            strVista &= "" & "       dataType:""json""," & vbCrLf
            strVista &= "" & "       success: function(respuesta) {" & vbCrLf
            strVista &= "" & "" & vbCrLf
            strVista &= "" & strEditarTraeDatos & vbCrLf
            strVista &= "" & "            " & vbCrLf
            strVista &= "" & "        }" & vbCrLf
            strVista &= "" & "" & vbCrLf
            strVista &= "" & "    });" & vbCrLf
            strVista &= "" & "" & vbCrLf
            strVista &= "" & "})" & vbCrLf


            strVista &= "" & "</script>" & vbCrLf
            Return strVista
        Catch ex As Exception
            ' SI NO SE ABRE LA CONEXIÓN MANDAMOS MENSAJE DE ERROR
            MsgBox("ERROR " & ex.Message)

            Exit Function
        End Try

    End Function

End Module

Como ejecutar una consulta MySQL y ciclo While en Visual Basic 2022

Ya hemos visto como realizar la conexión a la base de datos MySQL / MariaDB además de conectarnos con una cadena de conexión dinámica ahora veremos como realizar una consulta a una table y leer los datos con el ciclo While.

Estamos en en el archivo modulo crearModelo.vb justo despues de abrir la conexión declaramos la variable comando de tipo mysqlcommand, y ejecutaremos la siguiente consulta “describe proveedores;” la cual nos regresa los campos de la tabla, quedaría de la siguiente forma.

 Dim comando = New MySqlConnector.MySqlCommand("describe proveedores;", connection)

Posteriormente guardamos el resultado usando la función executeReader

Dim resultado = comando.ExecuteReader

En resultado tenemos guardado todos los renglones y columnas que nos regreso la consulta “describe proveedores;” para leerlos y mostrarlos en un MessageBox necesitaremos recorrerlos mediante un ciclo while y lo hacemos de la siguiente forma.

   While (resultado.Read)

      MessageBox.Show(resultado.GetString(0))

   End While
Vemos como el messageBox se muestra dependiendo del numero de columnas que tenga la tabla a la cual le hicimos el describe

Al final el código quedaría de la siguiente forma

'IMPORTAMOS LAS LIBRERIAS NECESARIAS PARA LA CONEXIÓN A MYSQL/MARIADB
Imports MySqlConnector.MySqlConnection

'EMPIEZA EL MODULO
Module crearModelo

    ' CON PUBLIC SUB CREAMOS PROCEDIMIENTOS
    Public Sub generaModelo()

        ' VARIABLES PARA LA CONEXIÓN
        Dim strServidor As String
        Dim strBaseDeDatos As String
        Dim strUsuario As String
        Dim strContra As String


        'OBTENEMOS LOS DATOS DE CONFIGURACIÖN DEL REGISTRO DE WINDOWS PREVIAMENTE GUARDADAS
        If Not My.Computer.Registry.GetValue("HKEY_CURRENT_USER\CREADORMVCPHP", "servidor", Nothing) Is Nothing Then
            strServidor = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\CREADORMVCPHP", "servidor", Nothing).ToString()
            strBaseDeDatos = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\CREADORMVCPHP", "baseDeDatos", Nothing).ToString()
            strUsuario = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\CREADORMVCPHP", "usuario", Nothing).ToString()
            strContra = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\CREADORMVCPHP", "contra", Nothing).ToString()
        Else

            MsgBox("No se han capturado la conexión a la base de datos")
            Return

        End If


        ' METEMOS LA CADENA DE CONEXIÓN EN UNA VARIABLE
        Dim cadenaConexion = "Server=" & strServidor & ";User ID=" & strUsuario & ";Password=" & strContra & ";Database=" & strBaseDeDatos

        ' CREAMOS LA CONEXIÓN CON LA CADENA DE CONEXIÓN
        Dim connection = New MySqlConnector.MySqlConnection(cadenaConexion)

        Try

            ' SI SE ABRE LA CONEXIÓN MANDAMOS MENSAJE
            connection.Open()


            Dim comando = New MySqlConnector.MySqlCommand("describe proveedores;", connection)

            Dim resultado = comando.ExecuteReader

            While (resultado.Read)

                MessageBox.Show(resultado.GetString(0))


            End While


            MsgBox("Conexion Correcta")

        Catch ex As Exception
            ' SI NO SE ABRE LA CONEXIÓN MANDAMOS MENSAJE DE ERROR
            MsgBox("ERROR " & ex.Message)

            Exit Sub
        End Try

    End Sub

End Module

ACTUALIZAR IMAGEN EN CAMPO MYSQL

Ya hicimos el insert en la base de datos del archivo de la imagen, tambien la mostramos en las vistas, ahora sigue hacer la modificacion “UPDATE” en la base de datos
FORO

https://foro.cesarsystems.com.mx/
DISCORD

https://discord.gg/7cJSkMxA

FACEBOOK
https://www.facebook.com/rasec555

TWITTER
https://twitter.com/JulioLeyvaR

CHANNEL TELEGRAM
https://telegram.me/CesarSystems

PAGINA WEB
https://cesarsystems.com.mx

TWITCH
https://www.twitch.tv/bardack21

DLIVE
https://dlive.tv/JulitoLeyva

ODYSEE
https://odysee.com/@JulioCesarLeyvaRodriguez:9

SCRIPT PARA DESBLOQUEAR PUERTO DE MYSQL MARIADB

Que tal mis amigos, en esta ocación les dejo un tutorial de primaria en el cual consiste liberar el puerto del MySQL o MariaDB, para que nos podamos conectar al servido de la base de datos desde cualquier equipo que este dentro de la red, aunque tambien les puede servir para cualquier otro puerto.

Para empezar les dejo el código .BAT que hay que ejecutar para que lo tengan guardado, si de dan cuenta en el numero de puerto dice 3316 tanto como en el segundo y tercer renglón, eso ustedes lo cambian por el 3306 si es que tenian el puerto por default de MySQL.

Archivo BAT

DESACTIVAR LA SENSIBILIDAD A MAYUSCULAS Y MINUSCULAS EN MARIADB

Cuando estamos trabajando en diferentes entonces como por ejemplo a veces en Windows y otras veces en Linux las configuraciones del servidor del MariaDB no se instalan de la misma manera en Linux y Windows, de eso nos percatamos con la configuración de la sensibilidad de las mayúsculas y minúsculas.

Cuando se hace la instalación en Windows a MariaDB no es sensible a las mayúsculas y minúsculas, en cambio en Linux Mint si es sensible y es por ello que se pueden dan problemas.

Una de las soluciones es desactivar la sensibilidad en MariaDB que se ha instalado en Linux para ello pondremos esta linea en el archivo de configuración lower_case_table_names = 1 en la sección de [mysqld].

CARGANDO MILLONES DE REGISTROS EN UNA TABLA VIA AJAX Y SERVER SIDE #56

Buenas tardes amigos, les dejo este video en donde vemos como meter 3 millones de registros a la tabla bitácora para que posteriormente hagamos pruebas para leer rápidamente la información mediante server side

COMO CREAR UN INSTALADOR PARA MONTAR EL MARIADB(MYSQL) CON BASE DE DATOS

Nos ha pasado que cuando desarrollamos un software queremos que en la implementación de este sea fácil instalar la base de datos para que la distribución e instalación sea mas fácil para los usuarios.

Una de las cosas que hemos querido hacer es que el servicio de la base de datos sea fácil y transparente de hacer, es decir, que se instale con un solo clic y empezar a usar el software.

Para ello mostraremos en esta entrada como instalar el servicio de base de datos de MariaDB MySQL“, con las base de datos y tablas con la información ya insertada, así como la configuración de usuarios  etc.

Para empezar, los archivos originales se obtuvieron de la paquetera de XAMPP, el cual contiene PHP, MySQL, Apache, lo cual solo vamos a sacar es el MySQL, Pueden descargar XAMPP en esta pagina.

Una vez que ya tengan montada si información sus tablas triggers y configuraciones empezaremos para crear nuestra instalación.

Una vez instalado podemos sacar la carpeta del MySQL C:\xampp\mysql, podemos mover la carpeta del MySQL a C:\MySQL.

Como hemos cambiado de dirección nuestra carpeta ya que antes estaba en C:\xampp\mysql y ahora esta en C:\MySQL necesitamos cambiar el archivo de configuración llamado My.ini que esta en C:\MySQL\BIN\My.ini, tienen que cambiar la ruta del archivo y directorios, solo pongan la ruta nueva que en este ejemplo seria socket          = “C:/mysql/mysql.sock” , y así en todo el archivo.

Ahora tenemos que crear el archivo .bat que va a crear e iniciar el servicio del MySQL, en caso de que algo salga mal eliminamos el servicio con la siguiente instrucción en la consola de comando “SC delete MySQL“.

Para crear el archivo lo dejaremos de la siguiente forma, una disculpa, les dejo el código en imagen, no he puesto el resaltador de código.

Con este código instalara el servicio y lo montara una vez que sea instalado.

Ahora a que crear el instalador, se puede hacer el instalador con InnoSetup pero en esta ocación lo haremos de una manera mas fácil y funcional lo haremos con Winrar lo pueden descargar haciendo clic aquí.

Primero comprimiremos la carpeta seleccionando los archivos y le damos añadir al archivo y en la primera pestaña activaremos el check crear autoextraible.

Luego vamos a la pestaña Avanzado y damos clic en autoextraible en en la carpeta de extracción pondremos lo siguiente %SYSTEMDRIVE%\MySQL\ lo que hará es buscar el disco duro donde esta instalado el sistema operativo y allí pondrá la carpeta del MySQL y extraerá allí los archivos.
Luego nos vamos a instalacion y alli en el campo de texto de instalación pondremos %SYSTEMDRIVE%\MySQL\mysql_serviceinstall.bat que es lo que se va a ejecutar después de haber extraído los datos.
Damos aceptar y ya se creara el exe de instalación, solo tendrán que ejecutar el exe como administrador y funcionara correctamente.

COMO LEER UNA TABLA Y PONER LOS DATOS EN UN JTABLE EN JAVA

Que tal camaradas en este post les dejare un ejemplo de como leer una tabla en MySQL a travez de un procedimiento almacenado y poner los datos en un JTable que es el equivalente al grid en las IDE de Microsoft o las mas parecida que encontre.

En primera necesitaremos del procedimiento almacenado el cual les dejo aquí mismo

[code language=”SQL”]

DROP PROCEDURE IF EXISTS `PA_LeeClientes`$$
CREATE PROCEDURE `PA_LeeClientes`(IN `desde` BIGINT, IN `cuantos` BIGINT, IN `Busqueda` VARCHAR(200))
BEGIN

SELECT right(`Clientes`.`idCliente`,5) as idCliente,
`Clientes`.`Nombres`,
`Clientes`.`Apellidos`,
`Clientes`.`Direccion`,
`Clientes`.`Ciudad`,
`Clientes`.`Telefono`,
`Clientes`.`RFC`,
`Clientes`.`FechaNacimiento`,
`Clientes`.`Estado`,
`Clientes`.`Municipio`,
`Clientes`.`CodigoPostal`
FROM `Clientes`
where Nombres LIKE CONCAT(‘%’,Busqueda,’%’)
or Nombres LIKE CONCAT(‘%’,Busqueda,’%’)
or Apellidos LIKE CONCAT(‘%’,Busqueda,’%’)
or Direccion LIKE CONCAT(‘%’,Busqueda,’%’)
or Ciudad LIKE CONCAT(‘%’,Busqueda,’%’)
or Telefono LIKE CONCAT(‘%’,Busqueda,’%’)
or RFC LIKE CONCAT(‘%’,Busqueda,’%’)
or Estado LIKE CONCAT(‘%’,Busqueda,’%’)
limit desde,cuantos;
[/code]

Ahora un método que necesitaremos es la que esta el la clase “Clientes”
[code language=”Java”]
public void leerClientes(long intDesde ,long intCuantos,DefaultTableModel tablaClientes,String strBusqueda ){
String strConsulta;
String datos[]=new String [4];

strConsulta="call PA_LeeClientes("+intDesde+","+intCuantos+",’"+strBusqueda+"’);";

try{

ps= con.conectado().prepareStatement(strConsulta);
res = ps.executeQuery();

while(res.next()){
//System.out.println(res.getString("Nombres"));
datos[0]=res.getString("IdCliente");
datos[1]=res.getString("Nombres");
datos[2]=res.getString("Apellidos");
datos[3]=res.getString("RFC");

tablaClientes.addRow(datos);
}
res.close();
}catch(SQLException e){
System.out.println(e);

}

}
[/code]

Y por si hiciera falta la clase de conexión a la base de datos MySQL
[code language=”Java”]

Ahora vemos el método que forma el JTable y le asigna los datos
[code language="Java"]
public void defineTablaClientes(String strBusqueda,long DesdeHoja){

long lngRegistros=1;
long lngDesdeRegistro;

//DEFINIMOS LA TABLA MODELO
DefaultTableModel tablaClientes = new DefaultTableModel();

//LE AGREGAMOS EL TITULO DE LAS COLUMNAS DE LA TABLA EN UN ARREGLO
String strTitulos[]={"ID CLIENTE","NOMBRE","APELLIDO","RFC"};

//LE ASIGNAMOS LAS COLUMNAS AL MODELO CON LA CADENA DE ARRIBA
tablaClientes.setColumnIdentifiers(strTitulos);

//LE ASIGNAMOS EL MODELO DE ARRIBA AL JTABLE
this.JTabClientes.setModel(tablaClientes);

//AHORA A LEER LOS DATOS

//ASIGNAMOS CUANTOS REGISTROS POR HOJA TRAEREMOS
lngRegistros=(Long.valueOf(this.txtNumReg.getText()));

//ASIGNAMOS DESDE QUE REGISTRO TRAERA LA CONSULTA SQL
lngDesdeRegistro=(DesdeHoja*lngRegistros)-lngRegistros;

//INSTANCEAMOS LA CLASE CLIENTE
control_cliente classCliente= new control_cliente();

//LEEMOS LA CLASE CLIENTE MANDANDOLE LOS PARAMETROS
classCliente.leerClientes(lngDesdeRegistro, (Long.valueOf(this.txtNumReg.getText())),tablaClientes,strBusqueda);

//LE PONEMOS EL RESULTADO DE LA CONSULA AL JTABLE
this.JTabClientes.setModel(tablaClientes);

//ASIGNAMOS LOS VALORES A LA PAGINACION
lngRegistros = classCliente.leerCuantos("");
lngNumPaginas= (lngRegistros/ (Long.valueOf( this.txtNumReg.getText())))+1;
this.jlblTotalPaginas.setText(" De " + ( lngNumPaginas));

}
[/code]

Y de esta manera sencilla se agregan los valores a la celda, es muy fácil verdad.

Bien camaradas espero que les sirva y saludos

COMO CONECTAR JAVA CON MYSQL NETBEANS EJEMPLO #4

Bienvenidos sean otra vez a este post, lo que hoy se vendrá a explicar sera la manera de como conectar, enlazar, ligar un programa escrito en Java, lógicamente desde el código fuente, a una base de datos MySQL 5.6.X

La versión del MySQL es la versión que viene en la instalación de XAMPP 5.6.11.

Primeramente tendrán que instalar el MySQL, cualquiera de estos videomanuales te pueden servir, uno es para Linux Mint 17.2 Rafaela y otro es para la versión de Windows 10.

Instalación Windows 10

[youtube https://www.youtube.com/watch?v=7oFXfcPP9CE]

Instalación Linux Mint 17.2
[youtube https://www.youtube.com/watch?v=8yuUw0V7jz0]

Una vez instalado el servidor SQL procederemos a levantar la base de datos

[code languaje=”sql”]
— phpMyAdmin SQL Dump
— version 4.4.12
— http://www.phpmyadmin.net

— Servidor: localhost
— Tiempo de generación: 12-10-2015 a las 05:06:49
— Versión del servidor: 5.6.25
— Versión de PHP: 5.6.11

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;


— Base de datos: `INVEN`

CREATE DATABASE IF NOT EXISTS `INVEN` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `INVEN`;

DELIMITER $$

— Procedimientos

DROP PROCEDURE IF EXISTS `sp_InsertaCliente`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_InsertaCliente`(in Nombres VARCHAR(200)
, Apellidos VARCHAR(200),Direccion varchar(200),Ciudad varchar(200)
,Telefono varchar(200),RFC VARCHAR(10),FechaNacimiento VARCHAR(200),Estado VARCHAR(200)
,Municipio varchar(200),CodigoPostal VARCHAR(200))
BEGIN

INSERT INTO `Clientes`
(
`Nombres`,
`Apellidos`,
`Direccion`,
`Ciudad`,
`Telefono`,
`RFC`,
`FechaNacimiento`,
`Estado`,
`Municipio`,
`CodigoPostal`
)
VALUES
(
Nombres,
Apellidos,
Direccion,
ciudad,
Telefono,
RFC,
FechaNacimiento,
Estado,
Municipio,
CodigoPostal
);

END$$

DELIMITER ;

— ——————————————————–


— Estructura de tabla para la tabla `Clientes`

DROP TABLE IF EXISTS `Clientes`;
CREATE TABLE IF NOT EXISTS `Clientes` (
`idCliente` bigint(20) NOT NULL,
`Nombres` varchar(100) DEFAULT NULL,
`Apellidos` varchar(45) DEFAULT NULL,
`Direccion` varchar(45) DEFAULT NULL,
`Ciudad` varchar(45) DEFAULT NULL,
`Telefono` varchar(45) DEFAULT NULL,
`RFC` varchar(45) DEFAULT NULL,
`FechaNacimiento` datetime(6) DEFAULT NULL,
`Estado` varchar(45) DEFAULT NULL,
`Municipio` varchar(45) DEFAULT NULL,
`CodigoPostal` varchar(45) DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=latin1;


— Volcado de datos para la tabla `Clientes`

[/code]

Ya levantada la base de datos tendremos que agregar la siguiente librería para conectar MySQL mysql-connector-java-5.1.6-bin.jar, la agregamos de igual modo que hemos estado agregando librerías en los post anteriores.

Bien ya agregada la librería creamos la siguiente clase

[code languaje=”Java”]
/*
Clase conexión, recibe la información de la conexión y se conecta
*/
package herramientas;
import java.sql.*;
import javax.swing.JOptionPane;

public class conexion {

public static String strServidor= new String();
public static String strBaseDeDatos=new String();
public static String strUsuarioSQL=new String();
public static String strPSWSQL=new String();
Connection conexion= null;

public Connection conectado(){
try{

Class.forName("com.mysql.jdbc.Driver");

conexion = DriverManager.getConnection("jdbc:mysql://"+ this.strServidor +"/" +this.strBaseDeDatos + "?user="+this.strUsuarioSQL + "&password="+ this.strPSWSQL);
Statement stm = conexion.createStatement();
}
catch(SQLException e)
{

JOptionPane.showMessageDialog(null, "ERROR DE CONEXIÓN"+e);

}
catch(ClassNotFoundException e)
{
JOptionPane.showMessageDialog(null, e);
}
return conexion;
}

public void desconectar(){
conexion = null;
System.out.println("conexion terminada");

}

}

[/code]

Luego al usar la clase conexión, lo haríamos de la siguiente forma

[code languaje=”Java”]
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package interfaces;

import clases.classUsuarios;

//AQUI ES DONDE TENEMOS LA CLASE CONEXION
import herramientas.conexion;

import java.awt.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.jar.Attributes;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

import javax.xml.*;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
*
* @author julio
*/
public class frmLogueo extends javax.swing.JFrame {

/**
* Creates new form frmLogueo
*/
public frmLogueo() {
initComponents();
leerConfiguracion();
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jLabel2 = new javax.swing.JLabel();
lblServidor = new javax.swing.JLabel();
txtServer = new javax.swing.JTextField();
lblUsuario = new javax.swing.JLabel();
txtUsuario = new javax.swing.JTextField();
lblContraseña = new javax.swing.JLabel();
cmdAccesar = new javax.swing.JButton();
pswContraseña = new javax.swing.JPasswordField();
lblBase = new javax.swing.JLabel();
txtBase = new javax.swing.JTextField();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setAlwaysOnTop(true);
setLocationByPlatform(true);
setResizable(false);

jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/padlock.jpg"))); // NOI18N

lblServidor.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
lblServidor.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblServidor.setText("SERVIDOR");
lblServidor.setToolTipText("");

lblUsuario.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
lblUsuario.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblUsuario.setText("USUARIO");

lblContraseña.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
lblContraseña.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblContraseña.setText("CONTRASEÑA");

cmdAccesar.setText("ACCESO");
cmdAccesar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdAccesarActionPerformed(evt);
}
});

lblBase.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
lblBase.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblBase.setText("BASE DE DATOS");
lblBase.setToolTipText("");

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(129, 129, 129)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lblServidor, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
.addComponent(txtUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
.addComponent(lblUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
.addComponent(pswContraseña)
.addComponent(txtServer, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
.addComponent(lblContraseña, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblBase, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
.addComponent(txtBase)))
.addGroup(layout.createSequentialGroup()
.addGap(114, 114, 114)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(123, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(140, 140, 140)
.addComponent(cmdAccesar, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(156, Short.MAX_VALUE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addGap(30, 30, 30)
.addComponent(lblServidor)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lblBase)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtBase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
.addComponent(lblUsuario)
.addGap(12, 12, 12)
.addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lblContraseña)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(pswContraseña, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(93, 93, 93))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(459, Short.MAX_VALUE)
.addComponent(cmdAccesar, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap()))
);

pack();
setLocationRelativeTo(null);
}// </editor-fold>

private void cmdAccesarActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:

// File archivoConexion = new File("Conexion.xml");
//
// if (archivoConexion.exists())
// System.out.println("El fichero");
// else
crearXML2();

//AQUI CREAMOS LA INSTANCIA A LA CLASE
conexion con = new conexion();

//AQUI LLENAMOS CON LOS DATOS NECESARIOS DE CONEXIÓN
con.strServidor=this.txtServer.getText();
con.strPSWSQL="";
con.strUsuarioSQL="root";
con.strBaseDeDatos=this.txtBase.getText();

//AQUI REALIZAMOS LA CONEXIÓN
con.conectado();

leerConfiguracion();
frmPrincipal principal= new frmPrincipal();
classUsuarios usuarios = new classUsuarios();

//ESTO YA ES OTRA HISTORIA, AQUI VERIFICA SI EL USUARIO Y CONTRASEÑA COINCIDEN
if (usuarios.blnChecaUsuarioContra("SELECT * FROM Usuarios where Usuario=’"+this.txtUsuario.getText() +"’ and Contra=’"+this.pswContraseña.getText()+"’")==true){
this.setVisible(false);
principal.setVisible(true);
}
else
JOptionPane.showMessageDialog(null, "USUARIO O CONTRASEÑA INCORRECTO"+this.pswContraseña.getText());
System.out.println("SELECT * FROM Usuarios where Usuario=’"+this.txtUsuario.getText() +"’ and Contra=’"+this.pswContraseña.getText()+"’");
} catch (ParserConfigurationException ex) {
Logger.getLogger(frmLogueo.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerException ex) {
Logger.getLogger(frmLogueo.class.getName()).log(Level.SEVERE, null, ex);
}

}

/**
* @param args the command line arguments
*/
// public static void main(String args[]) {
// /* Set the Nimbus look and feel */
// //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
// /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
// * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
// */
// try {
// for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
// if ("Nimbus".equals(info.getName())) {
// javax.swing.UIManager.setLookAndFeel(info.getClassName());
// break;
// }
// }
// } catch (ClassNotFoundException ex) {
// java.util.logging.Logger.getLogger(frmLogueo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (InstantiationException ex) {
// java.util.logging.Logger.getLogger(frmLogueo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (IllegalAccessException ex) {
// java.util.logging.Logger.getLogger(frmLogueo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (javax.swing.UnsupportedLookAndFeelException ex) {
// java.util.logging.Logger.getLogger(frmLogueo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// }
// //</editor-fold>
//
// /* Create and display the form */
// java.awt.EventQueue.invokeLater(new Runnable() {
// public void run() {
// new frmLogueo().setVisible(true);
// }
// });
// }

// Variables declaration – do not modify
private javax.swing.JButton cmdAccesar;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel lblBase;
private javax.swing.JLabel lblContraseña;
private javax.swing.JLabel lblServidor;
private javax.swing.JLabel lblUsuario;
private javax.swing.JPasswordField pswContraseña;
private javax.swing.JTextField txtBase;
private javax.swing.JTextField txtServer;
private javax.swing.JTextField txtUsuario;
// End of variables declaration

public void crearXML2() throws ParserConfigurationException, TransformerConfigurationException, TransformerException{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
DOMImplementation implementation = builder.getDOMImplementation();

Document document = implementation.createDocument(null, "Configuracion", null);
document.setXmlVersion("1.0");

Element raiz = document.getDocumentElement();

Element nodoServidor = document.createElement("Servidor"); //creamos un nuevo elemento
Text nodoValorServidor = document.createTextNode(this.txtServer.getText()); //Ingresamos la info
nodoServidor.appendChild(nodoValorServidor);
raiz.appendChild(nodoServidor); //pegamos el elemento a la raiz "Documento"

Element nododb = document.createElement("DB"); //creamos un nuevo elemento
Text nodoValorDB = document.createTextNode(this.txtBase.getText()); //Ingresamos la info
nododb.appendChild(nodoValorDB);
raiz.appendChild(nododb); //pegamos el elemento a la raiz "Documento"

Element nodoUsuario = document.createElement("Usuario"); //creamos un nuevo elemento
Text nodoValorUsuario = document.createTextNode(this.txtUsuario.getText()); //Ingresamos la info
nodoUsuario.appendChild(nodoValorUsuario);
raiz.appendChild(nodoUsuario); //pegamos el elemento a la raiz "Documento"

Source source = new DOMSource(document);
StreamResult result = new StreamResult(new java.io.File("Conexion.xml"));//nombre del archivo
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(source, result);
}

public void leerConfiguracion(){
try{
File fXmlFile = new File("Conexion.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);

//optional, but recommended
//read this – http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

NodeList nList = doc.getElementsByTagName("Configuracion");

System.out.println("—————————-");

for (int temp = 0; temp < nList.getLength(); temp++) {

Node nNode = nList.item(temp);

System.out.println("nCurrent Element :" + nNode.getNodeName());

if (nNode.getNodeType() == Node.ELEMENT_NODE) {

Element eElement = (Element) nNode;

this.txtServer.setText( eElement.getElementsByTagName("Servidor").item(0).getTextContent());
this.txtBase.setText(eElement.getElementsByTagName("DB").item(0).getTextContent());
this.txtUsuario.setText(eElement.getElementsByTagName("Usuario").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

}

[/code]

Por si llegaran a necesitar la clase usuarios
[code languaje=”Java”]
/*
CREADO POR JULIO
*/
package clases;

import java.sql.SQLException;
import herramientas.conexion.*;
import com.sun.crypto.provider.RSACipher;
import herramientas.conexion;
import java.awt.List;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @author julio
*/
public class classUsuarios {

private conexion con;
PreparedStatement ps;
ResultSet res;

public classUsuarios() {
con = new conexion();
}

public boolean blnChecaUsuarioContra( String sql){
boolean data =false;
String idUsuarios="IdUsuarios";

try{

ps= con.conectado().prepareStatement(sql);
res = ps.executeQuery();

while(res.next()){
//System.out.println(res.getNString(idUsuarios));
data=true;
System.out.println(res.getWarnings());
}
res.close();
}catch(SQLException e){
System.out.println(e);

}
return data;
}

}

[/code]

Página 6 de 6

Creado con WordPress & Tema de Anders Norén