LinuxParty

NUESTRO SITIO necesita la publicidad para costear hosting y el dominio. Por favor considera deshabilitar tu AdBlock en nuestro sitio. También puedes hacernos una donación entrando en linuxparty.es, en la columna de la derecha.

Ratio: 4 / 5

Inicio activadoInicio activadoInicio activadoInicio activadoInicio desactivado

MySQL es el sistema de administración de bases de datos SQL más ampliamente utilizado en proyectos LAMP (Linux/Apache/MySQL/PHP).

Pin It

Ratio: 4 / 5

Inicio activadoInicio activadoInicio activadoInicio activadoInicio desactivado

La forma más fácil de seguir este tutorial es utilizar un cliente de línea de comandos / cliente SSH (como PuTTY para Windows) y simplemente copiar y pegar los comandos (excepto donde hay que proporcionar información propia como direcciones IP, nombres de host, contraseñas, ...). Esto ayuda a evitar errores tipográficos.

Cómo montar la replicación de base de datos de MySQL

En este tutorial se describe cómo configurar la replicación de bases de datos en MySQL. La replicación MySQL le permite tener una copia exacta de una base de datos desde un servidor maestro en otro servidor (esclavo), y todas las actualizaciones de la base de datos en el servidor principal se replican inmediatamente en la base de datos en el servidor esclavo para que ambas bases de datos están en sintonía. Esto no es una política de copia de seguridad, ya que un accidente emitido mediante el comando DELETE también se llevará a cabo en el esclavo, pero la replicación puede ayudar a proteger contra fallos de hardware.

Pin It

Ratio: 5 / 5

Inicio activadoInicio activadoInicio activadoInicio activadoInicio activado

2 Configure el esclavo

En el esclavo, primero tenemos que crear la base de datos exampledb:

mysql -u root -p
Enter password:
CREATE DATABASE exampledb;
quit;


Si has hecho un volcado SQL de exampledb en el maestro y lo ha trasladado al esclavo, entonces es el momento ahora de importar el volcado SQL en nuestro recién creado exampledb en el esclavo:

mysql -u root -p<password> exampledb < /path/to/exampledb.sql

Si quieres usar LOAD DATA FROM MASTER, forma, entonces no hay nada que usted debe hacer en estos momentos.


Ahora tenemos que decirle al MySQL esclavo que es el esclavo, que el maestro es 192.168.0.100, y que la base de datos principal a tener en cuenta es exampledb. Por lo tanto, añadir las siguientes líneas a /etc/mysql/my.cnf:

server-id=2
master-host=192.168.0.100
master-user=slave_user
master-password=secret
master-connect-retry=60
replicate-do-db=exampledb

Luego reinicie MySQL:

 

/etc/init.d/mysql restart

 


Si no ha importado la base de datos del maestro exampledb con la ayuda de un volcado SQL,  entonces usar LOAD DATA FROM MASTER; ahora para obtener los datos de la base de datos exampledb del maestro:

mysql -u root -p
Enter password:
LOAD DATA FROM MASTER;
quit;

Si tiene phpMyAdmin instalado en el esclavo puede comprobar si todas las tablas / datos de exampledb del maestro también están disponibles en el esclavo exampledb.


Por último, debemos hacer lo siguiente:

mysql -u root -p
Enter password:
SLAVE STOP;

En el comando siguiente (aún en el shell de MySQL) tiene que sustituir los valores de forma adecuada:

 

CHANGE MASTER TO MASTER_HOST='192.168.0.100', MASTER_USER='slave_user', MASTER_PASSWORD='<some_password>', MASTER_LOG_FILE='mysql-bin.006', MASTER_LOG_POS=183;

 

  • MASTER_HOST es la dirección IP o el nombre del maestro (en este ejemplo, es 192.168.0.100).
  • MASTER_USER es el usuario al que se le otorgan privilegios de replicación en el maestro.
  • MASTER_PASSWORD es la contraseña de MASTER_USER en el maestro.
  • MASTER_LOG_FILE es el archivo de MySQL devuelto al ejecutar SHOW MASTER STATUS; en el maestro.
  • MASTER_LOG_POS es la posición MySQL devuelta al ejecutar SHOW MASTER STATUS; en el maestro.

Ahora todo lo que queda por hacer es iniciar el esclavo. Todavía en el shell de MySQL escriba:

START SLAVE;
quit;

¡Eso es! Ahora, cada vez exampledb se actualice en el maestro, todos los cambios se replican en exampledb en el esclavo. Pruébelo!

 


PREVIO:Cómo replicar una de base de datos de MySQL (1 de 2)

 


 

Pin It
Inicio desactivadoInicio desactivadoInicio desactivadoInicio desactivadoInicio desactivado

mylvmbackup es un script en Perl para crear rápidamente copias de seguridad de MySQL. Utiliza la función snapshot (instantánea) de LVM para hacerlo. Para realizar una copia de seguridad, mylvmbackup obtiene un bloqueo de lectura en todas las tablas y flushes de todo servidor almacenado caché en disco, crea una instantánea del volumen que contiene el directorio de datos de MySQL y abre nuevamente las tablas. Este artículo muestra cómo usarlo en un servidor Ubuntu 12.10.

Pin It

Ratio: 5 / 5

Inicio activadoInicio activadoInicio activadoInicio activadoInicio activado

Es posible que usted se encuentre en la situación de tener que supervisar un servidor MySQL de forma remota. Hay algunas herramientas Linux para hacer este desempeño y seguimiento de consultas a nivel local, y estas herramientas también pueden utilizarse para supervisar a distancia -pero no cifrado temporalmente- También a menudo MySQL escucha la interfaz de bucle de retorno (loopback o localhost), por lo que ni siquiera es accesible remotamente a través de la red (que es muy buena idea desde el punto de vista de seguridad). Pero hay una solución fácil en el mundo Linux.

Pin It
Inicio desactivadoInicio desactivadoInicio desactivadoInicio desactivadoInicio desactivado

Sergei de MariaDB está especulando acerca de algunos cambios dentro de MySQL 5.5.27. Parece que los nuevos testcases no están incluidas en MySQL, lo que deja a los desarrolladores que dependen de ellos sin actividad. "¿Significa esto que los casos de pruebas ya no están incluidos? Oracle no respondió a mi pregunta. Pero de hecho, hay evidencia de que esta suposición podría ser cierta. Por ejemplo, este e-mail de confirmación que muestra nuevos casos de prueba, de hecho, van en esta guía "interna", que no está incluido en la distribución de código abierto de MySQL.

Pin It

Ratio: 5 / 5

Inicio activadoInicio activadoInicio activadoInicio activadoInicio activado
Código:
Option Compare Database
Option Explicit

' exportSQL version 2.0
' www.cynergi.net/prod/exportsql/
'
'
'Un caso muy común, como en mi caso, al comenzar a utilizar MySQL, necesitaba migrar mis
'bases de datos desde Access a MySQL. La solución a este problema, nos la aporta un
'módulo creado por Pedro Freire de CYNERGI.
'
'Los pasos que debemos seguir para instalar este módulo, y su posterior uso son:
'
'   1. Abre el archivo de Access .mdb que deseas exportar.
'   2. En la ventana de objetos de la BD selecciona "Módulos", y después en "Nuevo".
'   3. Entonces se te abrirá una ventana nueva, borra todo texto (código) que haya escrito.
'   4. Copia todo el texto del archivo de Pedro Freire y pégalo en el nuevo módulo.
'   5. Cierra la ventana de código del módulo, selecciona que "Sí" desea guardar los
'   cambios y nombra el módulo (p.e. "MexportSQL"). El módulo es ahora parte de tu
'   base de datos Access
'   6. Vuelve a abrir el módulo, o pincha con el ratón en "Diseño" con nuestro nuevo módulo
'    seleccionado. Mueve el cursor hasta donde aparezca la primera palabra "Function",
'    y presiona F5 o selecciona "Ejecutar" en el menú.
'
'La ejecución del módulo nos creará dos archivos (esql_add.txt y esql_del.txt) en el
'    directorio C:\temp (el que trae por defecto, pero lo podemos cambiar).
'   (y que debe existir) A nosotros el archivo que nos interesa es esql_add.txt,
'   el cuál como mejor nos parezca deberemos llevarnoslo a nuestra máquina Linux.
'
'Ahora solo tenemos que seguir los paso que explicamos en el capítulo anterior:
'
'   1. Creamos la base de datos: mysqladmin create mybd
'   2. Volamos los datos y la nueva base de datos: cat esql_add.txt | mysql mybd
'
' (C) 1997-98 CYNERGI - www.cynergi.net, Esta dirección de correo electrónico está siendo protegida contra los robots de spam. Necesita tener JavaScript habilitado para poder verlo.
' (C) Pedro Freire - Esta dirección de correo electrónico está siendo protegida contra los robots de spam. Necesita tener JavaScript habilitado para poder verlo.  (do not add to mailing lists without permission)
'
' This code is provided free for anyone's use and is therefore without guarantee or support.
' This does NOT mean CYNERGI delegates its copyright to anyone using it! You may change the
' code in any way, as long as this notice remains on the code and CYNERGI is notified (if you
' publish the changes: if your changes/corrections prove valuable and are added to the code,
' you will be listed in a credit list on this file).
'
' You may NOT sell this as part of a non-free package:
' IF YOU HAVE PAID FOR THIS CODE, YOU HAVE BEEN ROBBED! CONTACT Esta dirección de correo electrónico está siendo protegida contra los robots de spam. Necesita tener JavaScript habilitado para poder verlo.!

' MODULE
'   "exportSQL"
'
' GOAL
'   Export all tables in a MS-Access database file to 2 text files:
'   one containing SQL instructions to delete the new tables to be created,
'   and the other with SQL instructions to create and insert data into
'   the new tables. The table structure and data will resemble as much as
'   possible the current Access database.
'
' HOW TO USE
'   Copy-and-paste this text file into an Access module and run the first
'   (and only public) function. in more detail, you:
'   * Open the Access .mdb file you wish to export
'   * in the default database objects window, click on "Modules", and then on "New"
'   * The code window that opens has some pre-written text (code). Delete it.
'   * Copy-and-paste this entire file to the code module window
'   * You may hit the compile button (looks like 3 sheets of paper with an arrow on
'     top of them, pressing down on them), or select Debug, Compile Loaded Modules
'     from the top menu, just to make sure there are no errors, and that this code
'     works on your Access version (it works on Access'97 and should work on Access'95)
'   * Close the code module window - windows will prompt you to save the code:
'     answer "Yes", and when promped for a name for the module, type anything
'     (say, "MexportSQL")
'   The module is now part of your Access database. To run the export, you:
'   * Re-open the code module (by double-clicking on it, or clicking "Design"
'     with it selected). Move the cursor to where the first "Function" keyword appears.
'     Press F5 or select Run, Go/Continue from the top menu.
'   * Alternativelly, click on "Macros" on the database objects window,
'     and then on "New". On the macro window, select "RunCode" as the macro action,
'     and "exportSQL" as the function name, bellow. Save the macro similarly to the
'     module, and this time double-clicking on it, or clicking "Run" will run the export.
'
' BEFORE RUNNING THE EXPORT
'   Before running the export, be sure to check out the Export Options just bellow this
'   text, and change any according to your wishes and specs.
'
' TECH DATA
'   Public identifiers:
'   * Only one: "exportSQL", a function taking and returning no arguments. It runs the export.
'   Functionallity:
'   * Can export to mSQL v1, mSQL v2 or MySQL-recognised SQL statements
'   * Excellent respect for name conversion, namespace verification, type matching, etc.
'   * Detects default values "=Now()", "=Date()" and "=Time()" to create types like "TIMESTAMP"
'   * Fully configurable via private constants on top of code
'   * Exports two files: one for erasures, another for creations (useful when updating dbs)
'   * Generates compatibility warnings when necessary
'   * Code and generated files are paragraphed and easy to read
'   * Access text and memo fields can have any type of line termination: \n\r, \r\n, \n or \r
'   * Properly escapes text and memo fields, besides all types of binary fields
'   * Closes all open objects and files on error
'   * Known bugs / incomplete constructs are signalled with comments starting with "!!!!"
'   * Two alternatives on absent date/time type on mSQL: REAL or CHAR field


' Export Options - change at will

Private Const DB_ENGINE As String = "MY"  ' USE ONLY "M1" (mSQL v1), "M2" (mSQL v2) or "MY" (MySQL)
Private Const DB_NAME As String = ""  ' Use empty string for current. Else use filename or DSN name of database to export
Private Const DB_CONNECT As String = ""  ' Used only if above string is not empty
Private Const MSQL_64kb_AVG As Long = 2048  ' ALWAYS < 65536 (to be consistent with MS Access). Set to max expected size of Access MEMO field (to preserve space in mSQL v1)
Private Const WS_REPLACEMENT As String = "_"  ' Use "" to simply eat whitespaces in identifiers (table and field names)
Private Const IDENT_MAX_SIZE As Integer = 19  ' Suggest 64. Max size of identifiers (table and field names)
Private Const PREFIX_ON_KEYWORD As String = "_"  ' Prefix to add to identifier, if it is a reserved word
Private Const SUFFIX_ON_KEYWORD As String = ""  ' Suffix to add to identifier, if it is a reserved word
Private Const PREFIX_ON_INDEX As String = "ix"  ' Prefix to add to index identifier, to make it unique (mSQL v2)
Private Const SUFFIX_ON_INDEX As String = ""  ' Suffix to add to index identifier, to make it unique (mSQL v2)
Private Const ADD_SQL_FILE As String = "c:\temp\esql_add.txt"  ' Use empty if open on #1. Will be overwritten if exists!
Private Const DEL_SQL_FILE As String = "c:\temp\esql_del.txt"  ' Use empty if open on #2. Will be overwritten if exists!
Private Const LINE_BREAK As String = "\n"  ' Try "<br>". String to replace line breaks in text fields
Private Const QUERY_SEPARATOR As String = ";"  ' Terminator/separator of SQL queries (to instruct some monitor program to execute them)
Private Const COMMENT_PREFIX As String = "#"  ' Use empty string for no comments
Private Const DISPLAY_WARNINGS As Boolean = True  ' False to output the warnings to the files, only
Private Const DATE_AS_STR As Boolean = True  ' False to use real number data type for date, time and timestamp (in mSQL only)
Private Const PARA_INSERT_AFTER As Integer = 3  ' Field count after which print INSERTs different lines
Private Const INDENT_SIZE As Integer = 5  ' Number of spaces on indents


' Global var to store inter-funtion data
Private warnings As String  ' Not an option: do not set in any way


' Primary Export Function

Sub exportSQL()
On Error GoTo exportSQL_error

    Dim cdb As Database
    Dim ctableix As Integer, ctablename As String

    If DB_NAME = "" Then
        Set cdb = CurrentDb()
    Else
        Set cdb = OpenDatabase(DB_NAME, False, True, DB_CONNECT) ' Shared, read-only
    End If
   
    If ADD_SQL_FILE <> "" Then Open ADD_SQL_FILE For Output As #1
    If DEL_SQL_FILE <> "" Then Open DEL_SQL_FILE For Output As #2

    DoCmd.Hourglass True

    If COMMENT_PREFIX <> "" Then
        Print #1, COMMENT_PREFIX & " Exported from MS Access to " & IIf(Left$(DB_ENGINE, 2) = "MY", "MySQL", "mSQL")
        Print #1, COMMENT_PREFIX & " (C) 1997-98 CYNERGI - www.cynergi.net, Esta dirección de correo electrónico está siendo protegida contra los robots de spam. Necesita tener JavaScript habilitado para poder verlo."
        Print #1,
   
        Print #2, COMMENT_PREFIX & " Exported from MS Access to " & IIf(Left$(DB_ENGINE, 2) = "MY", "MySQL", "mSQL")
        Print #2, COMMENT_PREFIX & " (C) 1997-98 CYNERGI - www.cynergi.net, Esta dirección de correo electrónico está siendo protegida contra los robots de spam. Necesita tener JavaScript habilitado para poder verlo."
        Print #2,
    End If

    'Go through the table definitions
    For ctableix = 0 To cdb.TableDefs.Count - 1
   
        Dim cfieldix As Integer, cfieldname As String
        Dim fieldlst As String, sqlcode As String
        Dim primary_found As Boolean
        Dim crs As Recordset
   
        ' Let's take only the visible tables
        If (((cdb.TableDefs(ctableix).Attributes And DB_SYSTEMOBJECT) Or _
        (cdb.TableDefs(ctableix).Attributes And DB_HIDDENOBJECT))) = 0 Then
           
            ctablename = conv_name("" & cdb.TableDefs(ctableix).Name)
           
            Print #2,
            Print #2, "DROP TABLE " & ctablename & QUERY_SEPARATOR
           
            ' CREATE clause
            Print #1,
            Print #1, "CREATE TABLE " & ctablename
            Print #1, Space$(INDENT_SIZE) & "("
           
            warnings = ""
            fieldlst = ""
            primary_found = False
           
            ' loop thorugh each field in the table
            For cfieldix = 0 To cdb.TableDefs(ctableix).Fields.Count - 1
               
                Dim typestr As String, fieldsz As Integer, dvstr As String
                Dim found_ix As Boolean, cindex As Index, cfield As Field
               
                ' if this is not the first iteration, add separators
                If fieldlst <> "" Then
                    fieldlst = fieldlst & ", "
                    Print #1, ","
                End If
               
                ' get field name
                cfieldname = conv_name("" & cdb.TableDefs(ctableix).Fields(cfieldix).Name)
                fieldlst = fieldlst & cfieldname
               
                ' translate types
                If DB_ENGINE = "M1" Or DB_ENGINE = "M2" Then
                    Select Case cdb.TableDefs(ctableix).Fields(cfieldix).Type
                        Case dbChar
                            typestr = "CHAR(" & cdb.TableDefs(ctableix).Fields(cfieldix).Size & ")"
                        Case dbText
                            fieldsz = cdb.TableDefs(ctableix).Fields(cfieldix).Size
                            If fieldsz = 0 Then fieldsz = 255
                            typestr = "CHAR(" & fieldsz & ")"
                        Case dbBoolean, dbByte, dbInteger, dbLong
                            typestr = "INT"
                        Case dbDouble, dbFloat, dbSingle
                            typestr = "REAL"
                        Case dbCurrency, dbDecimal, dbNumeric
                            typestr = "REAL"
                            warn "In new field '" & cfieldname & "', currency/BCD will be converted to REAL - there may be precision loss!", False
                        Case dbDate
                            typestr = IIf(DATE_AS_STR, "CHAR(19)", "REAL") ' use Access internal format: IEEE 64-bit (8-byte) FP
                            warn "In new field '" & cfieldname & "', date/time/timestamp will be converted to " & typestr & ".", False
                        Case dbTime
                            typestr = IIf(DATE_AS_STR, "CHAR(8)", "REAL") ' use Access internal format: IEEE 64-bit (8-byte) FP
                            warn "In new field '" & cfieldname & "', date/time/timestamp will be converted to " & typestr & ".", False
                        Case dbTimeStamp
                            typestr = IIf(DATE_AS_STR, "CHAR(19)", "REAL") ' use Access internal format: IEEE 64-bit (8-byte) FP
                            warn "In new field '" & cfieldname & "', date/time/timestamp will be converted to " & typestr & "." & IIf(DB_ENGINE = "M2", " Consider using pseudo field '_timestamp'.", ""), False
                        Case dbMemo
                            If DB_ENGINE = "M2" Then
                                typestr = "TEXT(" & MSQL_64kb_AVG & ")"
                            Else
                                typestr = "CHAR(" & MSQL_64kb_AVG & ")"
                                warn "In new field '" & cfieldname & "', dbMemo is not supported by mSQL v1 - fields larger than MSQL_64kb_AVG (" & MSQL_64kb_AVG & ") will not be accepted!", False
                            End If
                        Case dbBinary, dbVarBinary
                            typestr = "CHAR(255)"
                            warn "In new field '" & cfieldname & "', dbBinary and dbVarBinary are not supported by mSQL! - will use a text (CHAR(255)) field.", True
                        Case dbLongBinary
                            typestr = "CHAR(" & MSQL_64kb_AVG & ")"
                            warn "In new field '" & cfieldname & "', dbLongBinary is not supported by mSQL! - will use a text (CHAR(" & MSQL_64kb_AVG & ")) field.", True
                        Case Else
                            warn "In new field '" & cfieldname & "', dbBigInt and dbGUID are not currently supported!", True
                            Error 5  ' invalid Procedure Call
                    End Select
                Else
                    Select Case cdb.TableDefs(ctableix).Fields(cfieldix).Type
                        Case dbBinary
                            typestr = "TINYBLOB"
                        Case dbBoolean
                            typestr = "TINYINT"
                        Case dbByte
                            typestr = "TINYINT UNSIGNED"
                        Case dbChar
                            typestr = "CHAR(" & cdb.TableDefs(ctableix).Fields(cfieldix).Size & ")"
                        Case dbCurrency
                            typestr = "DECIMAL(20,4)"
                        Case dbDate
                            typestr = "DATETIME"
                        Case dbDecimal
                            typestr = "DECIMAL(20,4)"
                        Case dbDouble
                            typestr = "REAL"
                        Case dbFloat
                            typestr = "REAL"
                        Case dbInteger
                            typestr = "SMALLINT"
                        Case dbLong
                            typestr = "INT"
                        Case dbLongBinary
                            typestr = "LONGBLOB"
                        Case dbMemo
                            typestr = "LONGBLOB"  ' !!!!! MySQL bug! Replace by LONGTEXT when corrected!
                        Case dbNumeric
                            typestr = "DECIMAL(20,4)"
                        Case dbSingle
                            typestr = "FLOAT"
                        Case dbText
                            fieldsz = cdb.TableDefs(ctableix).Fields(cfieldix).Size
                            If fieldsz = 0 Then fieldsz = 255
                            typestr = "CHAR(" & fieldsz & ")"
                        Case dbTime
                            typestr = "TIME"
                        Case dbTimeStamp
                            typestr = "TIMESTAMP"
                        Case dbVarBinary
                            typestr = "TINYBLOB"
                        Case dbBigInt, dbGUID
                            warn "In new field '" & cfieldname & "', dbBigInt and dbGUID are not currently supported!", True
                            Error 5  ' invalid Procedure Call
                        Case Else
                            typestr = "LONGBLOB"
                    End Select
                End If
               
                ' check not null and auto-increment properties
                If ((cdb.TableDefs(ctableix).Fields(cfieldix).Attributes And dbAutoIncrField) <> 0) Then
                    If Left$(DB_ENGINE, 2) = "MY" Then
                        typestr = typestr & " NOT NULL AUTO_INCREMENT"
                    Else
                        typestr = typestr & " NOT NULL"
                        warn "In new field '" & cfieldname & "', mSQL does not support auto-increment fields! - they will be pure INTs." & IIf(DB_ENGINE = "M2", " Consider using pseudo field '_rowid' or SEQUENCEs.", ""), False
                    End If
                ElseIf cdb.TableDefs(ctableix).Fields(cfieldix).Required = True Then
                    typestr = typestr & " NOT NULL"
                End If
                   
                ' default value
                dvstr = cdb.TableDefs(ctableix).Fields(cfieldix).DefaultValue
                If dvstr <> "" Then
                    If Left$(DB_ENGINE, 2) <> "MY" Then
                        warn "In new field '" & cfieldname & "', mSQL does not support default values! - they won't be initialised.", False
                    ElseIf cdb.TableDefs(ctableix).Fields(cfieldix).Required = False Then
                        warn "In new field '" & cfieldname & "', MySQL needs NOT NULL to support default values! - it won't be set a default.", False
                    ElseIf Left$(dvstr, 1) = """" Then
                        typestr = typestr & " DEFAULT '" & conv_str(Mid$(dvstr, 2, Len(dvstr) - 2)) & "'"
                    ElseIf ((LCase(dvstr) = "now()" Or LCase(dvstr) = "date()" Or LCase(dvstr) = "time()") And _
                    (Left$(typestr, 5) = "DATE " Or Left$(typestr, 5) = "TIME " Or Left$(typestr, 9) = "DATETIME ")) Then
                        typestr = "TIMESTAMP " & Right$(typestr, Len(typestr) - InStr(typestr, " "))
                    ElseIf LCase(dvstr) = "no" Then
                        typestr = typestr & " DEFAULT 0"
                    ElseIf LCase(dvstr) = "yes" Then
                        typestr = typestr & " DEFAULT 1"
                    Else
                        typestr = typestr & " DEFAULT " & dvstr
                    End If
                End If
               
                ' check if primary key (for mSQL v1)
                If DB_ENGINE = "M1" Then
                    found_ix = False
                    For Each cindex In cdb.TableDefs(ctableix).Indexes
                        If cindex.Primary Then
                            For Each cfield In cindex.Fields
                                If cfield.Name = cdb.TableDefs(ctableix).Fields(cfieldix).Name Then
                                    found_ix = True
                                    Exit For
                                End If
                            Next cfield
                            If found_ix Then Exit For
                        End If
                    Next cindex
                    If found_ix Then
                        If primary_found Then
                            warn "On new table '" & ctablename & "', mSQL v1 does not support more than one PRIMARY KEY! Only first key was set.", False
                        Else
                            typestr = typestr & " PRIMARY KEY"
                            primary_found = True
                        End If
                    End If
                End If
               
                'print out field info
                Print #1, Space$(INDENT_SIZE) & cfieldname & Space$(IDENT_MAX_SIZE - Len(cfieldname) + 2) & typestr;
           
            Next cfieldix
                 
            ' terminate CREATE clause
            If DB_ENGINE = "M2" Then
                Print #1,
                Print #1, Space$(INDENT_SIZE) & ")" & QUERY_SEPARATOR
            End If
                 
            ' primary key and other index declaration
            If DB_ENGINE = "M2" Or Left$(DB_ENGINE, 2) = "MY" Then
                For Each cindex In cdb.TableDefs(ctableix).Indexes
                    sqlcode = ""
                    For Each cfield In cindex.Fields
                        sqlcode = sqlcode & IIf(sqlcode = "", "", ", ") & conv_name(cfield.Name)
                    Next cfield
                    If DB_ENGINE = "M2" Then
                        Print #1, "CREATE " & IIf(cindex.Unique, "UNIQUE ", "") & "INDEX " & _
                        conv_name(PREFIX_ON_INDEX & cindex.Name & SUFFIX_ON_INDEX) & " ON " & _
                        ctablename & " (" & sqlcode & ")" & QUERY_SEPARATOR
                    Else
                        Print #1, ","
                        Print #1, Space$(INDENT_SIZE) & IIf(cindex.Primary, "PRIMARY ", "") & _
                        "KEY (" & sqlcode & ")";
                    End If
                Next cindex
            End If
           
            ' terminate CREATE clause
            If DB_ENGINE <> "M2" Then
                Print #1,
                Print #1, Space$(INDENT_SIZE) & ")" & QUERY_SEPARATOR
            End If

            ' print any warnings bellow it
            If COMMENT_PREFIX <> "" And warnings <> "" Then
                If DB_ENGINE = "M2" Then Print #1, COMMENT_PREFIX & " "
                Print #1, warnings
                warnings = ""
            End If
           
            Print #1,
           
            ' INSERT clause
            Set crs = cdb.OpenRecordset(cdb.TableDefs(ctableix).Name)
            If crs.RecordCount <> 0 Then
               
                ' loop thorugh each record in the table
                crs.MoveFirst
                Do Until crs.EOF
                   
                    ' start paragraphing
                    sqlcode = "INSERT INTO " & ctablename
                    If crs.Fields.Count > PARA_INSERT_AFTER Then
                        Print #1, sqlcode
                        If DB_ENGINE = "M1" Then Print #1, Space$(INDENT_SIZE) & "(" & fieldlst & ")"
                        Print #1, "VALUES ("
                        sqlcode = Space$(INDENT_SIZE)
                    Else
                        If DB_ENGINE = "M1" Then sqlcode = sqlcode & " (" & fieldlst & ")"
                        sqlcode = sqlcode & " VALUES ("
                    End If
                   
                    ' loop through each field in each record
                    For cfieldix = 0 To crs.Fields.Count - 1
                   
                        ' based on type, prepare the field value
                        If IsNull(crs.Fields(cfieldix).Value) Then
                            sqlcode = sqlcode & "NULL"
                        Else
                            Select Case crs.Fields(cfieldix).Type
                                Case dbBoolean
                                    sqlcode = sqlcode & IIf(crs.Fields(cfieldix).Value = True, "1", "0")
                                Case dbChar, dbText, dbMemo
                                    sqlcode = sqlcode & "'" & conv_str(crs.Fields(cfieldix).Value) & "'"
                                Case dbDate, dbTimeStamp
                                    If Left$(DB_ENGINE, 2) = "MY" Or DATE_AS_STR Then
                                        sqlcode = sqlcode & "'" & Format(crs.Fields(cfieldix).Value, "YYYY-MM-DD HH:MM:SS") & "'"
                                    Else
                                        'print in Access internal format: IEEE 64-bit (8-byte) FP
                                        sqlcode = sqlcode & "'" & Format(crs.Fields(cfieldix).Value, "#.#########") & "'"
                                    End If
                                Case dbTime
                                    If Left$(DB_ENGINE, 2) = "MY" Or DATE_AS_STR Then
                                        sqlcode = sqlcode & "'" & Format(crs.Fields(cfieldix).Value, "HH:MM:SS") & "'"
                                    Else
                                        'print in Access internal format: IEEE 64-bit (8-byte) FP
                                        sqlcode = sqlcode & "'" & Format(crs.Fields(cfieldix).Value, "#.#########") & "'"
                                    End If
                                Case dbBinary, dbLongBinary, dbVarBinary
                                    sqlcode = sqlcode & "'" & conv_bin(crs.Fields(cfieldix).Value) & "'"
                                Case Else
                                    sqlcode = sqlcode & conv_str(crs.Fields(cfieldix).Value)
                            End Select
                        End If
                       
                        ' paragraph separators
                        If cfieldix < crs.Fields.Count - 1 Then
                            sqlcode = sqlcode & ", "
                            If crs.Fields.Count > PARA_INSERT_AFTER Then
                                Print #1, sqlcode
                                sqlcode = Space$(INDENT_SIZE)
                            End If
                        End If
                       
                    Next cfieldix
                   
                    ' print out result and any warnings
                    sqlcode = sqlcode & IIf(crs.Fields.Count > PARA_INSERT_AFTER, " )", ")") & QUERY_SEPARATOR
                    Print #1, sqlcode
                    If COMMENT_PREFIX <> "" And warnings <> "" Then
                        Print #1, warnings
                        warnings = ""
                    End If
                    If crs.Fields.Count > PARA_INSERT_AFTER Then Print #1,
                   
                    crs.MoveNext
                Loop
               
            Else
               
                ' if there is no data on the table
                If COMMENT_PREFIX <> "" Then Print #1, COMMENT_PREFIX & " This table has no data"
           
            End If
           
            crs.Close
            Set crs = Nothing
       
        End If  'print only unhidden tables
   
    Next ctableix
   
exportSQL_exit:
    Close #2
    Close #1
   
    cdb.Close
    Set cdb = Nothing

    DoCmd.Hourglass False

    Exit Sub

exportSQL_error:
    MsgBox Err.Description
    Resume exportSQL_exit

End Sub


Private Function conv_name(strname As String) As String
    Dim i As Integer, str As String

    ' replace inner spaces with WS_REPLACEMENT
    str = strname
    i = 1
    While i <= Len(str)
        Select Case Mid$(str, i, 1)
            Case " ", Chr$(9), Chr$(10), Chr$(13)  ' space, tab, newline, carriage return
                str = Left$(str, i - 1) & WS_REPLACEMENT & Right$(str, Len(str) - i)
                i = i + Len(WS_REPLACEMENT)
            Case Else
                i = i + 1
        End Select
    Wend
    ' restrict tablename to IDENT_MAX_SIZE chars, *after* eating spaces
    str = Left$(str, IDENT_MAX_SIZE)
    ' check for reserved words
    conv_name = str
    If Left$(DB_ENGINE, 2) = "MY" Then
        Select Case LCase$(str)
            Case "add", "all", "alter", "and", "as", "asc", "auto_increment", "between", _
            "bigint", "binary", "blob", "both", "by", "cascade", "char", "character", _
            "change", "check", "column", "columns", "create", "data", "datetime", "dec", _
            "decimal", "default", "delete", "desc", "describe", "distinct", "double", _
            "drop", "escaped", "enclosed", "explain", "fields", "float", "float4", _
            "float8", "foreign", "from", "for", "full", "grant", "group", "having", _
            "ignore", "in", "index", "infile", "insert", "int", "integer", "interval", _
            "int1", "int2", "int3", "int4", "int8", "into", "is", "key", "keys", _
            "leading", "like", "lines", "limit", "lock", "load", "long", "longblob", _
            "longtext", "match", "mediumblob", "mediumtext", "mediumint", "middleint", _
            "numeric", "not", "null", "on", "option", "optionally", "or", "order", _
            "outfile", "partial", "precision", "primary", "procedure", "privileges", _
            "read", "real", "references", "regexp", "repeat", "replace", "restrict", _
            "rlike", "select", "set", "show", "smallint", "sql_big_tables", _
            "sql_big_selects", "sql_select_limit", "straight_join", "table", "tables", _
            "terminated", "tinyblob", "tinytext", "tinyint", "trailing", "to", "unique", _
            "unlock", "unsigned", "update", "usage", "values", "varchar", "varying", _
            "with", "write", "where", "zerofill"
                conv_name = Left$(PREFIX_ON_KEYWORD & str & SUFFIX_ON_KEYWORD, IDENT_MAX_SIZE)
                If (str = conv_name) Then
                    warn "In identifier '" & strname & "', the new form '" & strname & _
                    "' is a reserved word, and PREFIX_ON_KEYWORD ('" & _
                    PREFIX_ON_KEYWORD & "') and SUFFIX_ON_KEYWORD ('" & SUFFIX_ON_KEYWORD & _
                    "') make it larger than IDENT_MAX_SIZE, and after cut it is the same as the original! " & _
                    "This is usually caused by a void or empty PREFIX_ON_KEYWORD.", True
                    Error 5  ' invalid Procedure Call
                End If
        End Select
    End If
End Function


Private Function conv_str(str As String) As String
    Dim i As Integer, nlstr As String, rstr As Variant
   
    nlstr = ""
    rstr = Null
    i = 1
    While i <= Len(str)
        Select Case Mid$(str, i, 1)
            Case Chr$(0)  ' ASCII NUL
                nlstr = ""
                rstr = "\0"
            Case Chr$(8)  ' backspace
                nlstr = ""
                rstr = "\b"
            Case Chr$(9)  ' tab
                nlstr = ""
                rstr = "\t"
            Case "'"
                nlstr = ""
                rstr = "\'"
            Case """"
                nlstr = ""
                rstr = "\"""
            Case "\"
                nlstr = ""
                rstr = "\\"
            Case Chr$(10), Chr$(13)  ' line feed and carriage return
                If nlstr <> "" And nlstr <> Mid$(str, i, 1) Then
                    ' there was a previous newline and this is its pair: eat it
                    rstr = ""
                    nlstr = ""
                Else
                    ' this is a fresh newline
                    rstr = LINE_BREAK
                    nlstr = Mid$(str, i, 1)
                End If
            Case Else
                nlstr = ""
        End Select
        If Not IsNull(rstr) Then
            str = Left$(str, i - 1) & rstr & Right$(str, Len(str) - i)
            i = i + Len(rstr)
            rstr = Null
        Else
            i = i + 1
        End If
    Wend
    conv_str = str
End Function


Private Function conv_bin(str As String) As String
    Dim i As Integer, rstr As String
   
    rstr = ""
    i = 1
    While i <= Len(str)
        Select Case Mid$(str, i, 1)
            Case Chr$(0)  ' ASCII NUL
                rstr = "\0"
            Case Chr$(8)  ' backspace
                rstr = "\b"
            Case Chr$(9)  ' tab
                rstr = "\t"
            Case "'"
                rstr = "\'"
            Case """"
                rstr = "\"""
            Case "\"
                rstr = "\\"
            Case Chr$(10)  ' line feed
                rstr = "\n"
            Case Chr$(13)  ' carriage return
                rstr = "\r"
        End Select
        If rstr <> "" Then
            str = Left$(str, i - 1) & rstr & Right$(str, Len(str) - i)
            i = i + Len(rstr)
            rstr = ""
        Else
            i = i + 1
        End If
    Wend
    conv_bin = str
End Function


Private Sub warn(str As String, abortq As Boolean)
    If DISPLAY_WARNINGS Then MsgBox str, vbOKOnly Or vbExclamation, "Warning"
    warnings = warnings & COMMENT_PREFIX & " Warning: " & str & Chr$(13) & Chr$(10)
End Sub

Procede del artículo: Exportar Bases de Datos de Access (MDB) a MySQL

Pin It
Inicio desactivadoInicio desactivadoInicio desactivadoInicio desactivadoInicio desactivado
Para exportar una BBDD desde la consola: (Lo colocado entre corchetes "[ ]" puede ser opcional.")

mysqldump [-h ip_servidor] -u usuario_bd -p basededatos > fichero.sql

Para extraer una copia comprimida:

mysqldump -uUsuarioDB  -pPassword  -h  Host_o_IP   NombreDataBase  |  gzip -c > fichero.sql.gz


Y ahora, ¿cómo importaríamos este fichero.sql en otra base de datos?

(Bueno, si está comprimida, descomprimirla con: gzip -d fichero.sql.gz)

A mi, generalmente me gusta usar esta opción: (nota la base de datos "nombre_basedatos", debe existir) (Si no es así, sáltese este paso)

mysql -u usuario_mysql -p nombre_basedatos < fichero.sql

Pin It
Inicio desactivadoInicio desactivadoInicio desactivadoInicio desactivadoInicio desactivado
Oracle gana de nuevo algún karma entre la comunidad de código abierto mediante la liberación de clúster MySQL 7.2 con ambiciosas pretensiones de mejoras de rendimiento de hasta 70x. La nueva versión es GPL, y afirman que ha procesado más de mil millones de consultas por minuto. Los lectores pueden recordar la historia acerca de Oracle, y la adición de extensiones comerciales de MySQL".
Pin It
Inicio desactivadoInicio desactivadoInicio desactivadoInicio desactivadoInicio desactivado

Te recomendamos leas este artículo:

Cómo configurar MariaDB Galera Cluster 5.5 en CentOS, RHEL y Fedora

MySQL/Galera es una distribución de MySQL que puede utilizarse para crear un clúster de MySQL(InnoDB) con varios maestros sincrónicos. Se basa en el concepto de replicación optimista de conjunto de escritura y consiste en un parche servidor MySQL y Galera, un back-end de replicación genérico que implementa la interfaz WSREP. MySQL/Galera cuenta con verdadera capacidad con varios maestros, para que la misma tabla puede modificarse simultáneamente en distintos nodos. Es verdaderamente muy versatil, por lo que nunca se pierde una transacción confirmada. Es transparente a los disipadores (triggers), procedimientos almacenados y funciones definidas por el usuario. Es escalable incluso para cargas de escritura intensiva.

Pin It


Redes:



 

Suscribete / Newsletter

Suscribete a nuestras Newsletter y periódicamente recibirás un resumen de las noticias publicadas.

Donar a LinuxParty

Probablemente te niegues, pero.. ¿Podrías ayudarnos con una donación?


Tutorial de Linux

Filtro por Categorías