Giter Site home page Giter Site logo

mysqlbackupnet / mysqlbackup.net Goto Github PK

View Code? Open in Web Editor NEW
257.0 32.0 105.0 4.72 MB

A tool to backup and restore MySQL database in C#/VB.NET/ASP.NET.

License: The Unlicense

C# 96.74% CSS 1.02% JavaScript 0.71% ASP.NET 1.53%
mysql-database mysql-backup mysql mysql-export mysql-restore mysql-import csharp vbnet

mysqlbackup.net's People

Contributors

adriancs2 avatar trembon avatar wgawroniol avatar xoozoo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mysqlbackup.net's Issues

Control errors

how do you verify that the copy or restoration has been successful?
A greeting.

Can several DB be backup to one file? (Not issue)

Hello

First of all, thank you very much for your hard work.
I have been using the tool and its amazing.

I quick questions nevertheless. Is it possible to backup several databases to the same file?

Thanks in advance

Export with double quotes issue

Hi, thanks for your DLL that helped me alot.
Everything worked fine (Export and import without any issue)
But when I tried to insert any data to my table and export it, some of the backtick replaced with double quotes, example:

DROP TABLE IF EXISTS TestTable;
CREATE TABLE IF NOT EXISTS "TestTable" (
"ID" int(11) NOT NULL AUTO_INCREMENT,
"WW" int(6) NOT NULL,
"Date" varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
"UserID" varchar(40) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
"Amount" decimal(19,2) NOT NULL,

"These "TestTable", "ID", "WW" should come with backquote.
And restoring this backup.sql will give me error and drop all my table.
Hope I can understand why it happens?

Thanks for your hardworking!

MySqlConnection ambiguous v2.3.0.1

Hi I am using MySqlBackup.Net 2.3.0.1 in my .Net Core 2.2 project. Now I am keep getting the following error. Can you please help to see what could be wrong. I am also using Pomelo.EntityFrameworkCore which seems like uses the MySqlConnector. Thanks

error

Tables missing from export

When exporting a schema, some of the tables are not exported.

  • I can find nothing these missing tables have in common or anything making them different to the rest of the tables on the database (via Schema Inspector)
  • Running mysqldump from the server exports all tables
  • Exporting from MySql Workbench exports all tables
  • Default settings used in the export code (I used the sample code posted here with no changes)
  • No exception is thrown.
  • Have tried exporting without rows and the same tables were missing
  • MySqlData 8.0.16
  • MySqlBackup v 2.2.1
  • Same results whether exporting from the remote database or from a local copy
  • Engine is InnoDB
  • The table data is not in the exported file, so my issue is with export, not the subsequent import.
  • FWIW I have tried on two different computers with the same results

Here is the create table code for one of the tables that doesn't export:
CREATE TABLE plugin(idint(10) unsigned NOT NULL AUTO_INCREMENT,codevarchar(16) NOT NULL,namevarchar(64) NOT NULL,descriptionvarchar(256) DEFAULT NULL,copyofint(10) unsigned DEFAULT NULL,createdondatetime DEFAULT NULL,changedondatetime DEFAULT NULL,deletedondatetime DEFAULT NULL,changedby varchar(64) DEFAULT NULL, PRIMARY KEY (id), UNIQUE KEY code_UNIQUE (code), KEY fk_plugin_copyof_idx (copyof), CONSTRAINT fk_plugin_copyof FOREIGN KEY (copyof) REFERENCES plugin (id) ) ENGINE=InnoDB AUTO_INCREMENT=279 DEFAULT CHARSET=utf8;

Stored Procedures - DROP command problem on Stored Procedures

Great bit of code which saved me a lot of effort with mysqldump etc.

If the DEFINER user in the Stored Procedures is not the same as the database connection user all that happens when a table is dumped, with ".ExportProcedures" set to TRUE, is that the sql file generated contains a series of DROP commands (see below). This of course could be a major problem if the developer does not realise it will delete all the stored procedures in the destination database. So may need a change that if there is a user conflict that the DROP procedure is not generated to avoid undesired deletions from the destination database.

DROP PROCEDURE IF EXISTS queryname;
DELIMITER |
|
DELIMITER ;

Thanks - John

"mysql_error_log.txt" in application directory

When using the component a file named "mysql_error_log.txt" with the content "hi :)" is created in the application directory.
See MySqlBackup/MySqlBackup.cs -> Line 134
System.IO.File.WriteAllText("mysql_error_log.txt", "hi :)");

When uninstalling an application that includes the MySqlBackup.Net component, this file remains in the application directory. This will prevent the installer from removing the directory.

I assume it's a leftover from a debugging session, so is it possible to remove this line?

Thanks

Support for .Net Standard

Hello,
Are there any plans to support .Net Standard?
I tried to change the project to Standard 2.0 and added the MySql.Data 8.0.10-rc reference from Nuget without any compiler errors, but havent tested it yet.
So at first glance, there seems to be no code changes need to be made.

Error on restore events

Trying to restore a database backup with an event defined I got this message:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER |
CREATE EVENT EventDay1 ON SCHEDULE EVERY 1 YEAR STARTS ' at line 1
But trying to restore the same dump with mysql command the restore works fine.

Too high values on ExportProgressChanged event

Version: 2.1.3.59
Runtime: v4.0.30319
Project downloaded using GIT and compiled using Visual Studio 2017 Community version 15.9.8
No changes on source code

Issue: The ExportProgressChanged event carries incorrect information about the progress of the exported rows.

This is the code used for data export:

[...]
 using (MySqlBackup mb = new MySqlBackup(cmd))
 {
           mb.ExportInfo.AddCreateDatabase = true;
           mb.ExportInfo.ExportTableStructure = true;
           mb.ExportInfo.ExportRows = true;
           mb.ExportInfo.RecordDumpTime = true;
           mb.ExportInfo.ResetAutoIncrement = false;
           mb.ExportInfo.MaxSqlLength = 104857600; //100MB
           mb.ExportInfo.ExportFunctions = true;
           mb.ExportInfo.ExportProcedures = true;
           mb.ExportInfo.ExportTriggers = true;
           mb.ExportInfo.ExportEvents = true;
           mb.ExportInfo.ExportViews = true;
           mb.ExportInfo.ExportRoutinesWithoutDefiner = false;
           mb.ExportInfo.RowsExportMode = RowsDataExportMode.Insert;
           mb.ExportInfo.WrapWithinTransaction = false;
           mb.ExportProgressChanged += Mb_ExportProgressChanged;
           mb.ExportCompleted += Mb_ExportCompleted;
           mb.ExportToFile(Path.Combine(filePath));
 }
[...]

where Mb_ExportProgressChanged is:

 private void Mb_ExportProgressChanged(object sender, ExportProgressArgs e)
 {
             Console.WriteLine(e.CurrentRowIndexInAllTables + " " + e.TotalRowsInAllTables);
 }

This is the console result:

2459 26795
5856 26795
9252 26795
12594 26795
16142 26795
19874 26795
23169 26795
24708 26795
26060 26795
27930 26795   <------

As you can see the last value of CurrentRowIndexInAllTables is higher than TotalRowsInAllTables
I expected to have same value.

After mysqlbackup.net restores the sql file, the table names all become lowercase

I tested it again and confirmed that after mysqlbackup restores the sql file, there is a problem with the name of the table. My database is case-sensitive. The table names in my configured mysql5.7.22 are all uppercase letters.
After backing up with mysqldump, mysqldump restores and the table name does not change. But use mysqlbackup to restore the files backed up by mysqldump. After the restore, the table names all become lowercase.
I used mysqlbackup to back up the database, restore it with mysqldump, the table name is unchanged, or uppercase. This shows that mysqlbackup has problems with mysqldump compatibility, but mysqldump is perfectly compatible with mysqlbackup backup files.

This problem does not always appear, occasionally, may require multiple tests, to know how it is caused, will be related to spaces in the path, these times appeared 2-3 times.
When I tested it, I restored it to a different database. For example, the database name I backed up with mysqldump is test1. When I restore it, I use mysqlbackup to restore the backup database test1 to a new database test2.

InvalidOperationException using 'EnableEncryption'

Hi, excellent work, I'm using it without any problem, except when use "EnableEncryption" (and his password) in a medium database (about 42 226 KB), if I put "EnableEncryption" false all the prosess finish without troubles, if my database is shorter the problem still persist
the error is:
Collection was modified; enumeration operation may not execute

Source:
mscorlib

Stack trace:
en System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) en System.Collections.Generic.List'1.Enumerator.MoveNextRare() en MySql.Data.MySqlClient.MySqlBackup.Export_Procedures() en MySql.Data.MySqlClient.MySqlBackup.ExportStart() en MySql.Data.MySqlClient.MySqlBackup.ExportToFile(String filePath) en AppName.ControlDatosExternosClass.<>c__DisplayClass21_0.<CopiaRespaldoDB>b__0(Object s, DoWorkEventArgs args) en D:\RouteToTheFile\ControlDatosExternosClass.cs:línea 757

And the line 757 is just: Backup.ExportToFile(archivo);

The options I use is:
Backup.ExportInfo.EnableEncryption = true; Backup.ExportInfo.EncryptionPassword = "N7vngar45mDy5Cqxa"; Backup.ExportInfo.MaxSqlLength = 3145728; Backup.ExportInfo.AddCreateDatabase = false; Backup.ExportInfo.ExportProcedures = true; Backup.ExportInfo.ExportFunctions = true; Backup.ExportInfo.ExportTriggers = true; Backup.ExportInfo.WrapWithinTransaction = true; Backup.ExportInfo.ExportTableStructure = true; Backup.ExportInfo.ExportRows = true; Backup.ExportInfo.GetTotalRowsBeforeExport = true; Backup.ExportInfo.IntervalForProgressReport = 100; Backup.ExportInfo.RowsExportMode = RowsDataExportMode.Insert;

Access denied

When i click button to backup db it says access denied as runtime error how to grant administrator access

Help needed - Unable to export BLOB in Char Format

Hi developers/programmers,

Currently, MySqlBackup.NET only able to export BLOB field into HexString, which works fine. But however, I would like to provide another optional function: Export the BLOB field into binary char format, which is what MySqlDump does.

However, due to some unknown reason or missing steps, I'm unable to export the BLOB into char properly, which results altering of original bytes of the BLOB data.

Take this table as example:

CREATE TABLE `tableblob` (
  `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  `blobdata` MEDIUMBLOB,
  PRIMARY KEY (`id`)
)
ENGINE = InnoDB;

I am able to extract the BLOB from database and write it as follow:

blobexport

But, however, after the blob data was re-select out from database, the blob seems to be corrupted.

Any help would be appreciated.

I have attached the a sample project that specially built for running the test of this. You may use this project to perform the testing/debugging as well.

blob_debug.zip

You may look into the following files which the conversion of blob takes place:
\blob_debug\blob_debug\MySqlBackup.NET v2.3\Methods\QueryExpress.cs

Line 175: public static string ConvertToSqlFormat
Line 202: else if (ob is System.Byte[])

Thank you!

=====================
Related issue: #5

Weird exception after making a new backup

I'm getting a FileLoadException when executing Type.GetType after having created a backup using the library. This only happens after the backup is created, there is no issue before.

I've isolated the function that if executed causes the error to happen later and its new MySqlBackup(cmd) where cmd is MySql.Data.MySqlClient.MySqlCommand.

It's possible that the problem is caused by the line
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; ,
executed in the constructor of MySqlBackup.

Input string was not in a correct format

When dumping a very large database, the above error appears and only part of the database is dumped. If I keep trying, the database eventually finishes the backup. However, The software does not have someone in front of it at all times. What could be the cause of this?

About moving CodePlex articles

As you may know, CodePlex is shutting down this year.

Is it possible for you to move the articles to Github?

Thank you very much.

Memory

Hi,

After doing a export/import from memorystream my memory usage is more than 400MB

using (MemoryStream ms = new MemoryStream())
{
//export

//import

}

Exception "System.OutOfMemory" while restoring DB.

Hey,
So, I'm making a program that restores databases.

Ficheiro de backup: the .SQL file to restore.
Servidor: server.
Base de dados: Database.
Utilizador: user.
Porta: port.
Button "Restaurar" is "Restore".
I'm using your Mysql.data and Mysql.backup DLLs (MySQL Connector).

While it's restoring, it throws a 'System.OutOfMemoryException'. It shouldn't, I have 4GB of RAM, so I'm supposing that it's not a RAM problem.

Snippet of my code: https://ghostbin.com/paste/twq2d.
Stacktrace: https://ghostbin.com/paste/o5q2o
My SQL file is about 736MB.

(Using SharpDevelop, I can't debug line by line with F11, I don't know why though...)
capturar

Export tables separately

Good afternoon, I would like to know if there is how to export the tables separately, does each table generate its file?

Procedure Restore errors

I tryed to restore Stored Procedures with the Test Application and have SQL syntax errors on all procedures.

The Import_Routines() method gives exception errors for all of them.

I have made a Backup file named Test.sql that is attached in txt format
Test.txt

The resulting errors are displayed in the Error_Report.txt fila tha is also attached.
Error_Report.txt

Have you any suggestion to avoid this problem?

Many thanks for your attention

F. Prado

To do - v2.4

Convert ASCII null to \0
Fix BLOB to char conversion bug

Add feature:
ExportInfo.CombineInserts (bool) = false (do not combine inserts)
ExportInfo.SeparateInsertsByLineBreak (bool) = true

Add SQLite support

Not an issue. Functionality suggestion.

I've completed porting MySqlBackup.Net to SQLite. See repository https://github.com/Apskaita5/SQLiteBackup
Still needs some refactoring because I just copied your code and only made necessary changes to make it work with sqlite. Needs extensive testing also.
Would you like to merge projects?

Exception of type 'System.OutOfMemoryException' was thrown.

I am getting out of memory exception when calling function ExportToMemoryStream(ms) for large database?

Here is my code,

GC.Collect();
using (MySqlConnection con = new MySqlConnection(conBuilder.ToString()))
{
 using (MySqlCommand cmd = new MySqlCommand())
  {
   using (MySqlBackup mb = new MySqlBackup(cmd))
    {
     mb.ExportInfo.AddCreateDatabase = False;
     mb.ExportInfo.ExportTableStructure = True;
     mb.ExportInfo.ExportProcedures = True;
     mb.ExportInfo.ExportFunctions = True;
     mb.ExportInfo.ExportTriggers = True;
     mb.ExportInfo.ExportViews = True;

     cmd.Connection = con;
     con.Open();
     MemoryStream ms = new MemoryStream();
     mb.ExportToMemoryStream(ms); // ERROR: at this Out of Memory //
     ms.Position = 0;
     MemoryStream mszip = new MemoryStream();
     using (GZipStream zip = new GZipStream(mszip, CompressionMode.Compress, true))
      {
       byte[] buffer = ms.ToArray(); 
       zip.Write(buffer, 0, buffer.Length);
       zip.Flush();
       }
       mszip.Position = 0;
       // Client.PutObject('myflename.dump.Gzip',mszip);
       con.Close();
      }
     }
     con.Close();
    }

capture

Problem With Double Quotes

I have a problem when I export a database using this tool, the name of the table is in double quotes when is in the create statment, the right form is only in simple quotes, can anyone help me?
sin titulo

Exception "System.OutOfMemoryException" while memory stream exporting DB

Hello,

During export, an exception "System.OutOfMemoryException" throwing.

Stack Trace
System.IO.MemoryStream.set_Capacity(Int32 value) à System.IO.MemoryStream.EnsureCapacity(Int32 value) à System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count) à System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder) à System.IO.StreamWriter.Write(Char[] buffer, Int32 index, Int32 count) à System.IO.TextWriter.WriteLine(String value) à MySql.Data.MySqlClient.MySqlBackup.Export_RowsData_Insert_Ignore_Replace(String tableName, String selectSQL) à MySql.Data.MySqlClient.MySqlBackup.Export_RowsData(String tableName, String selectSQL) à MySql.Data.MySqlClient.MySqlBackup.Export_Rows(String tableName, String selectSQL) à MySql.Data.MySqlClient.MySqlBackup.Export_TableRows() à MySql.Data.MySqlClient.MySqlBackup.ExportStart() à MySql.Data.MySqlClient.MySqlBackup.ExportToMemoryStream(MemoryStream ms, Boolean resetMemoryStreamPosition) à MySql.Data.MySqlClient.MySqlBackup.ExportToMemoryStream(MemoryStream ms) à Pts.Framework.App.Autosoft.Database.Helper.DumpDatabaseWithEncrypt(String file, String connectionString) à AeOOut.For_SavPro.Act_Sav()

I can't use export to file because I can't write on disk…

I have 4GB of RAM, so I'm supposing that it's not a RAM problem.

MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error in your SQL syntax

I get this error with Triggers. In the backup,sql it has:

--
-- Dumping triggers
DROP TRIGGER /*!50030 IF EXISTS */ team_member_AINS;
DELIMITER |
CREATE TRIGGER team_member_AINS AFTER INSERT ON team_member FOR EACH ROW
INSERT INTO team_member_status_history VALUES (UUID(), NEW.Manager_code, NEW.Status, now()) |
DELIMITER ;

DROP TRIGGER /*!50030 IF EXISTS */ team_member_BUPD;
DELIMITER |
CREATE TRIGGER team_member_BUPD BEFORE UPDATE ON team_member FOR EACH ROW
BEGIN
IF NOT NEW.Status <=> OLD.Status THEN
INSERT INTO team_member_status_history VALUES (UUID(), NEW.Manager_code, NEW.Status, now());
END IF;
END |
DELIMITER ;

gets the errors as follows:

MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '|' at line 2
at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)
at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
at MySql.Data.MySqlClient.MySqlScript.Execute()
at MySql.Data.MySqlClient.MySqlBackup.Import_Routines()

MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 4
at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)
at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
at MySql.Data.MySqlClient.MySqlScript.Execute()
at MySql.Data.MySqlClient.MySqlBackup.Import_Routines()

Also get this for functions and procedures though for me that is not a concern currently.

Values of generated columns written to the backup file causes exception at restore

  • I have a generated column in a table:
    GeneratedColumn int(11) GENERATED ALWAYS AS (SomeExpression) STORED NOT NULL

  • The backup file from MySqlBackup.NET incorrectly contains:
    INSERT INTO MyTable ( otherColumns, GeneratedColumn ) VALUES ...

  • While the backup created by Export from MySQL workbench does not (correctly) contain the generated column values:
    INSERT INTO MyTable ( otherColumns ) VALUES ...

  • Therefore restore from MySqlBackup.NET file gives:
    MySql.Data.MySqlClient.MySqlException occurred
    HResult=0x80004005
    Message=The value specified for generated column 'GeneratedColumn' in table 'MyTable' is not allowed.
    StackTrace:
    at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
    at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
    at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)
    at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
    at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
    at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
    at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
    at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
    at MySql.Data.MySqlClient.MySqlScript.Execute()
    at MySql.Data.MySqlClient.MySqlBackup.Import_AppendLineAndExecute(String line)
    at MySql.Data.MySqlClient.MySqlBackup.Import_ProcessLine(String line)
    at MySql.Data.MySqlClient.MySqlBackup.Import_Start()
    at MySql.Data.MySqlClient.MySqlBackup.ImportFromTextReaderStream(TextReader tr, FileInfo fileInfo)
    at MySql.Data.MySqlClient.MySqlBackup.ImportFromFile(String filePath)

Stored Procedure Restore Fails from Generated SQL

Generated a SQL file containing a stored procedure using the ExportToFile function and then have tried to consume it using ImportFromFile which seems to resulting in a fail due You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line #.

From what I've seen it seems to be related to the delimiter that I'm currently using. Is there a possible workaround for this?

Only restore changes

I have an remote DB that I need to take a backup of every hour then restore a the local DB with the remote data, this may be outside of scope, but would is it possible to only restore the changes rather than the whole database, currently if I do a restore all the data is dropped and I don't have access to the data for 15 minutes or so every hour.

I think I'm potentially looking at this wrong and want to do a differential database backup.

Cheers.

What happens with concurrency?

Hi, thanks for your hard work, it saved me from a lot of issues I was having with mysqldump.
One question: What happens if the database is accesed or modified while I'm doing the back up? Do I need to lock the tables befores starting ?

Blob field

Migration have table __migrationhistory, field Model is a Blog, not export corret

MySqlBackup.Net:
image

WorkBench:
image

Foreign keys and table restore order

I'm porting the library to use with SQLite and noticed possible issue with foreign keys that make the table create order important. In MySQL foreign keys are created within table create statement. If the table referenced by a foreign key is not already in place, it would cause an exception. Same issue as with views/ methods dependencies.
Not sure, whether that should be handled by backup or restore.
Also capability to export/import only some tables creates dependency nightmare.

Mysqldump backup sql file with mysqlbackup.net restore will prompt an error:

Mysqldump backup sql file with mysqlbackup.net restore will prompt an error:

You have an error in your SQL syntax;check the manual that corresponds to your MySQL server version for the right syntax to use near "at line 3

Mysqldump backup sql can be restored with mysqldump
Mysqlbackup.net can also restore his own backup sql
I want to be a dual-engine software, I hope 2 backup and restore tools can be cross-mixed

Is there a way to solve?

Mysqldump backup command
Command = string.Format("mysqldump --quick --host={1} --default-character-set={2} -R -E --lock-tables --routines --force --port={3 } --user={4} --password={5} {6} -r "{0}"",
                            Directory, host, characterSet, port, user, password, databaseName);

Mysqlbackup.net restore command, no other parameters, keep the default

            characterSet = txtcharacterSet.Text.Trim();
            databaseName = cmbDBlist.Text.Trim();
            Host = txthost.Text.Trim();
            Password = txtpassword.Text;
            Port = txtport.Text.Trim();
            User = txtuser.Text.Trim();
            String ConnectString = String.Format("server={0};uid={1}; Port={2};pwd={3}; database={4};", host, user, port, password, databaseName) ;
            ConnectString += "charset=" + characterSet + "; " + "convertzerodatetime=true;";
            Try
            {
                Using (MySqlConnection myconn = new MySqlConnection(ConnectString))
                {
                    Using (MySqlCommand cmmd = new MySqlCommand())
                    {
                        Using (MySqlBackup backCmd = new MySqlBackup(cmmd))
                        {
 
                                cmmd.Connection = myconn;
                                    myconn.Open();
                                backCmd.ImportFromFile(strPath);

using dump table options

how can I use those options while dumping table to file

       --skip-add-drop-table
       --skip-add-locks            

Problem With Export DateTime Variables

First, thank you for great job.

I have found an issue exporting DateTime variables. I have studied the library a lite and I have found one solution.

In class QueryExpress, the function
public static string ConvertToSqlFormat(MySqlDataReader rdr, int colIndex, bool wrapStringWithSingleQuote, bool escapeStringSequence, MySqlColumn col)
where else if (ob is System.DateTime)

You do this to construct the string
`
if (wrapStringWithSingleQuote)
sb.AppendFormat("'");

            sb.AppendFormat(((DateTime)ob).ToString("yyyy-MM-dd HH:mm:ss", _dateFormatInfo));

            if (col.TimeFractionLength > 0)
            {
                sb.Append(".");
                string _microsecond = rdr.GetMySqlDateTime(colIndex).Microsecond.ToString();

                if (_microsecond.Length < col.TimeFractionLength)
                {
                    _microsecond = _microsecond.PadLeft(col.TimeFractionLength, '0');
                }
                else if (_microsecond.Length > col.TimeFractionLength)
                {
                    _microsecond = _microsecond.Substring(0, col.TimeFractionLength);
                }
                sb.Append(_microsecond.ToString().PadLeft(col.TimeFractionLength, '0'));
            }`

But rdr.GetMySqlDateTime(colIndex).Microsecond.ToString() returns a string with lenght equal to number of significant digits, that means:
If we have 0 microseconds, the string will be: "0"
If we have 8900 microseconds, the string will be: "8900"
If we have 384921 microseconds, the string will be: "384921"

So if col.TimeFractionLength = 3 (miliseconds) and we have 1 milisecond (1000 microseconds) rdr.GetMySqlDateTime(colIndex).Microsecond.ToString() returns "1000" and
else if (_microsecond.Length > col.TimeFractionLength) { _microsecond = _microsecond.Substring(0, col.TimeFractionLength); }
The string will be "100", and we will have convert 1ms to 100ms.

I have fixed the issue with this changes:
`
if (wrapStringWithSingleQuote)
sb.AppendFormat("'");

            sb.AppendFormat(((DateTime)ob).ToString("yyyy-MM-dd HH:mm:ss", _dateFormatInfo));

            if (col.TimeFractionLength > 0)
            {
                sb.Append(".");
                string _microsecond = rdr.GetMySqlDateTime(colIndex).Microsecond.ToString();

                _microsecond = _microsecond.PadLeft(6, '0');
                _microsecond = _microsecond.Substring(0, col.TimeFractionLength);
                sb.Append(_microsecond.ToString().PadLeft(col.TimeFractionLength, '0'));
            }`

Import views issues when restore

Hi, first of all, thank you very much for your hard work. I have been using the tool and its amazing.

But I have issues, when restore database with views by dependency errors (view does not exist). I fixed it adding code for create temporary tables as views (before to export views). I work it in version 2.0.9.2

I trying it in the new version, and it have the same issues to import views.

PD: Sorry for my bad english XD.
PD2: I attach the source code
MySqlBackup.zip

using Devart.data unstead of MySql.data

Dear adriancs2,
Thank you for this very helpfull project, Can i use Devart.data.dll unstead of Mysql.data.dll and how? because Mysql.data.dll is a GPL licensed
Kind Regard
Mohammed

Fatal error encountered during command execution

Hi, i am using MySqlBackup.NET, and during import i am getting the following error.
Any suggestion or similar situation encountered?

Message: Fatal error encountered during command execution.
StackTrace: at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
at MySql.Data.MySqlClient.MySqlScript.Execute()
at MySql.Data.MySqlClient.MySqlBackup.Import_AppendLineAndExecute(String line)
at MySql.Data.MySqlClient.MySqlBackup.Import_ProcessLine(String line)
at MySql.Data.MySqlClient.MySqlBackup.Import_Start()
at MySql.Data.MySqlClient.MySqlBackup.ImportFromTextReaderStream(TextReader tr, FileInfo fileInfo)
at MySql.Data.MySqlClient.MySqlBackup.ImportFromFile(String filePath)
at DatabaseBackUp.Program.ImportDatabase(String IPAddress, String DBName, Int32 Type, String Port) in Program.cs:line 1203
Source: MySql.Data
TargetSite: MySql.Data.MySqlClient.MySqlDataReader ExecuteReader(System.Data.CommandBehavior)

My code as follows.

using (MySqlBackup mb = new MySqlBackup(cmd))
                        {
                            cmd.Connection = conn;
                            //cmd.CommandTimeout = 0;
                            cmd.CommandTimeout = 1200;
                            conn.Open();
                            mb.ImportFromFile(file);
                            conn.Close();
                            SuccessFlag = true; 
                        }

Connection String
string constring = "SERVER=" + IPAddress + "; DATABASE=" + DBName + ";Port=" + Port + ";USER=123;PASSWORD=xxx;Convert Zero Datetime=True;Charset=utf8;";

Export error guid? help base size 1gb

does not load the database with such an error
Необработанное исключение типа "System.FormatException" в MySqlBackup.dll
Дополнительные сведения: Нераспознанный формат идентификатора GUID.
error after 30sec in mb.ExportToFile("ccvt_bot.sql");

using (MySqlConnection conn = new MySqlConnection("server=123.123.123.123;user=root;pwd=123123;database=ccvt_bot;charset=utf8;convertzerodatetime=true;")) { using (MySqlCommand cmd = new MySqlCommand()) { using (MySqlBackup mb = new MySqlBackup(cmd)) { cmd.Connection = conn; conn.Open(); cmd.CommandTimeout = 30; mb.ExportToFile("ccvt_bot.sql"); conn.Close(); } } }

image http://prntscr.com/odmuz6

MySql.Data Version

Is this still being maintained? MySql.Data Version v6.10.6. Outdated on Nuget. Great package though.

MySqlBackupNET doesn't export Stored Procedures

Hi,

First of all, great lib. Simple and clean.

However I'm having some troubles with the export function as it doesn't export any stored procedures.

There is this line:

-- 
-- Dumping procedures
-- 

but no stored procedures get exported.

I installed the Nuget package (MySqlBackup.Net 2.0.12) but because I'm using MySQL 8.0.11 which uses the 'caching_sha2_password' authentication type I get an error that the mysql.data.dll installed with MySqlBackup.Net does not support that authentication type.

So I installed Nuget package 'MySql.Data 8.0.12 from Oracle' to overwrite the mysql.data.dll which does support 'caching_sha2_password'.

After that exporting the database works, but the stored procedures are not in the export.
I tried adding mb.ExportInfo.ExportProcedures = true; but even with this, there are no stored procedures exported. There is no error either. Just an output with all the tables.

I don't know if the other mysql.data version has to do anything with it, but I add this information because it might.

Do you have any idea what the problem can be?

TINYINT broken values on restore

Backup file when restored messes up tinyint(1) values
e.g. 2 becomes 1 instead of 2
e.g. 3 becomes 1 instead of 3
But tinyint(4) values remain the same as it should

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.