Giter VIP home page Giter VIP logo

mysqlbackupnetcore's Introduction

MySQLBackupNetCore

A tool to backup and restore MySQL database in .NET 5 [.Net Core 5] Only.

Note

This is based on The Great Work of MySqlBackup.Net Thank You.

The reason I made this repo is I had a problem and this is the only way I solved it. use it in any way you see fit.

I choose not to do it in .net Standard for a reason.

It may work for you or it may not.

I Will Keep working on this code and make it better over time. if you have any idea you are welcome to be a contributor.

Every thing in MySqlBackup.Net also apply here.

Article at CodeProject.com

Download

Install via NuGet: PM> Install-Package MySQLBackupNetCore
https://www.nuget.org/packages/MySQLBackupNetCore/

Dependency

MySQLBackupNetCore stands on top of MySql.Data.DLL connector: Developped by MySQL (Oracle), https://dev.mysql.com/downloads/connector/net/.

Backup/Export a MySQL Database

string constring = "server=localhost;user=root;pwd=qwerty;database=test;";

// Important Additional Connection Options
constring += "charset=utf8;convertzerodatetime=true;";

string file = "C:\\backup.sql";

using (MySqlConnection conn = new MySqlConnection(constring))
{
    using (MySqlCommand cmd = new MySqlCommand())
    {
        using (MySqlBackup mb = new MySqlBackup(cmd))
        {
            cmd.Connection = conn;
            conn.Open();
            mb.ExportToFile(file);
            conn.Close();
        }
    }
}

Import/Restore a MySQL Database

string constring = "server=localhost;user=root;pwd=qwerty;database=test;";

// Important Additional Connection Options
constring += "charset=utf8;convertzerodatetime=true;";

string file = "C:\\backup.sql";

using (MySqlConnection conn = new MySqlConnection(constring))
{
    using (MySqlCommand cmd = new MySqlCommand())
    {
        using (MySqlBackup mb = new MySqlBackup(cmd))
        {
            cmd.Connection = conn;
            conn.Open();
            mb.ImportFromFile(file);
            conn.Close();
        }
    }
}

Introduction

MySQLBackupNetCore is a tool that can backup/restore MySQL database in .NET Programming Language. It is an alternative to MySqlDump.

This tool is developed in C# but able to be used in any .NET Language (i.e. VB.NET, F#, etc.).

Another benefit of making this tool is, we don't have to rely on two small programs - MySqlDump.exe and MySql.exe to perform the backup and restore task. We will have better control on the output result in .NET way.

The most common way to backup a MySQL Database is by using MySqlDump and MySQL Workbench.

MySQL Workbench is good for developers, but when comes to the client or end-user, the recommended way is to get every parameter preset and all they need to know is press the big button "Backup" and everything is done. Using MySQL Workbench as a backup tool is not a suitable solution for the client or end-user.

On the other hand, MySqlDump.exe cannot be executed directly from the Web Server. As most providers forbid that, MySqlBackup will be helpful in building a web-based (ASP.NET) backup tool.

Features

  • Backup and Restore of MySQL Database
  • Can be used in any .NET Languages.
  • Export/Import to/from MemoryStream
  • Conditional Rows Export (Filter Tables or Rows)
  • Progress Report is Available for Both Export and Import Task.
  • Able to export rows into different modes. (Insert, Insert Ignore, Replace, On Duplicate Key Update, Update)
  • Can be used directly in ASP.NET or web services.

Prerequisite and Dependencies for Development, Compile and Production Usage

MySQLBackupNetCore relies on the following component to work.

MySql.Data (Connector/NET)

Reminder

Reminder 1

MySQLBackupNetCore stands on top of MySql.Data.DLL which also stands on top of .NET Framework, which uses UTF8 encoding by default. If your database involves any UTF8 or Unicode Characters. You must use a MySQL database with default character of UTF8 while handling Unicode Characters, such as

  • Western European specific languages, the character of 'À', 'ë', 'õ', 'Ñ'.
  • Russian, Hebrew, India, Arabic, Chinese, Korean, Japanese characters, etc.

You are recommended to apply the connection string option of charset=utf8. Example:

server=localhost;user=root;pwd=mypwd;charset=utf8;

Reminder 2

DateTime conversion between MySQL and .NET Framework. In MySQL, there are various of DateTime format, such as null value or Date only data. But, in .NET Framework, there is no null value (or Date only) for DateTime. This error is not caused by MySqlBackup.DLL. MySql.Data.DLL (developed by Oracle) has decided to throw an exception of Data Conversion Error. Therefore, you are strongly recommended to apply the connection string option of convertzerodatetime=true. Example:

server=localhost;user=root;pwd=mypwd;charset=utf8;convertzerodatetime=true;

License

MySQLBackupNetCore is licensed under the The Unlicense.

mysqlbackupnetcore's People

Contributors

mohsalah66 avatar

Stargazers

 avatar

Watchers

 avatar  avatar

Forkers

bangush

mysqlbackupnetcore's Issues

datetime format incorrect

I have an issue with datetime format. I have the same databases (develop and production). Develop is local and prod is on hosting. I dont know why, but i can not dump production db.

Reason is, that i have

2023-02-01 17:04:22.1617|ERROR|MysqlBackup.Program|System.FormatException: Input string was not in a correct format.
at System.DateTimeFormat.FormatCustomized(DateTime dateTime, ReadOnlySpan1 format, DateTimeFormatInfo dtfi, TimeSpan offset, StringBuilder result) at System.DateTimeFormat.FormatStringBuilder(DateTime dateTime, ReadOnlySpan1 format, DateTimeFormatInfo dtfi, TimeSpan offset)
at System.DateTimeFormat.Format(DateTime dateTime, String format, IFormatProvider provider, TimeSpan offset)
at MySQLBackupNetCore.Methods.QueryExpress.ConvertToSqlFormat(Object ob, Boolean wrapStringWithSingleQuote, Boolean escapeStringSequence, MySqlColumn col, BlobDataExportMode blobExportMode)
at MySQLBackupNetCore.MySqlBackup.Export_GetValueString(MySqlDataReader rdr, MySqlTable table)
at MySQLBackupNetCore.MySqlBackup.Export_RowsData_Insert_Ignore_Replace(String tableName, String selectSQL)
at MySQLBackupNetCore.MySqlBackup.Export_RowsData(String tableName, String selectSQL)
at MySQLBackupNetCore.MySqlBackup.Export_Rows(String tableName, String selectSQL)
at MySQLBackupNetCore.MySqlBackup.Export_TableRows()
at MySQLBackupNetCore.MySqlBackup.ExportStart()
at MySQLBackupNetCore.MySqlBackup.ExportToFile(String filePath)
at MysqlBackup.Program.Test() in D:\Projekty\smallprograms\MysqlBackup\Program.cs:line 396

I think, that there is default format (at mysql) like 1.12.2023 00:15:26. I dont know hot to change it or fix.... I can not find differences between develop and prod.

I find, that datetime column is ok. Problem is with timestamp

Exception Unable to convert MySQL date/time value to System.DateTime when DateTime is 0000/00/00 00:00

Hello!
I'm having an issue with this package.
The database have like thousands of records and some of them I don't know why have some DateTime column with date like 0000/00/00 00:00 by mistake.
When I usually backup with Mysql Dump all goes normal, but using this package I'm facing this exception Unable to convert MySQL date/time value to System.DateTime when the record has this not empty but zero DateTime.

Otherwise all good and functionally. 👍

Nvm
Solved with

command += "charset=utf8;convertzerodatetime=true;";
Thanks in advance!

Object cannot be cast from DBNull to other types when conn.open

Software versions
Server type (MySQL, MariaDB, Aurora, etc.) and version: 10.11.2-MariaDB-log
.NET version: .NET 5.0

Describe the bug
When program try to connect, It crash... ("Object cannot be cast from DBNull to other types."

Exception
"Object cannot be cast from DBNull to other types."

at System.DBNull.System.IConvertible.ToInt32(IFormatProvider provider)
at MySql.Data.MySqlClient.Driver.LoadCharacterSets(MySqlConnection connection)
at MySql.Data.MySqlClient.Driver.Configure(MySqlConnection connection)
at MySql.Data.MySqlClient.MySqlConnection.Open()
at MysqlBackup.Program.ProcessServerExport(ConfigExclude excludeConfig, Server server) in D:\Projekty\smallprograms\MysqlBackup\Program.cs:line 145
at MysqlBackup.Program.Execute(Options opts) in D:\Projekty\smallprograms\MysqlBackup\Program.cs:line 90

Code sample
//connstring is with example values
constring = "server=myserver;Port=3306;user=userlogin;pwd="=password123456";database=dbName;convertzerodatetime=true;";
using (var conn = new MySqlConnection(constring))
{
using (var cmd = new MySqlCommand())
{
using (var mb = new MySqlBackup(cmd))
{
cmd.Connection = conn;
cmd.CommandTimeout = 99999;
conn.Open(); //here is the problem

/* A concise code sample to reproduce the bug */

Expected behavior
Normal connection. To other databases is ok, but i have one, where is problem.

The main problem is, that i can not change Mysql.Data to MysqlConnection. And new version ov MariaDB return null ID of collation.

see more mysql-net/MySqlConnector#1322

tinyint

I have a simple datatable. One column is tinyInt 1.
All exported rows has value 1 - but original data has 1,2,3... Why are the dump incorrect? What I have wrong?

output:
DROP TABLE IF EXISTS urop_degree;
CREATE TABLE IF NOT EXISTS urop_degree (
id int(11) NOT NULL AUTO_INCREMENT,
degree char(50) NOT NULL DEFAULT '',
sequence tinyint(3) DEFAULT NULL,
lodge tinyint(1) NOT NULL DEFAULT '0',
picture char(50) DEFAULT NULL,
active tinyint(1) NOT NULL DEFAULT '1',
svetlo1_c tinyint(3) unsigned DEFAULT NULL,
svetlo1_vc tinyint(3) unsigned DEFAULT NULL,
svetlo2_c tinyint(3) unsigned DEFAULT NULL,
svetlo2_vc tinyint(3) unsigned DEFAULT NULL,
svetlo3_c tinyint(3) unsigned DEFAULT NULL,
svetlo3_vc tinyint(3) unsigned DEFAULT NULL,
svetlo4_c tinyint(3) unsigned DEFAULT NULL,
svetlo4_vc tinyint(3) unsigned DEFAULT NULL,
navic_c tinyint(3) unsigned DEFAULT NULL,
navic_vc tinyint(3) unsigned DEFAULT NULL,
svetlo1_op tinyint(3) unsigned DEFAULT NULL,
svetlo2_op tinyint(3) unsigned DEFAULT NULL,
svetlo3_op tinyint(3) unsigned DEFAULT NULL,
svetlo4_op tinyint(3) unsigned DEFAULT NULL,
navic_op tinyint(3) unsigned DEFAULT NULL,
text text,
PRIMARY KEY (id),
KEY sequence (sequence)
) ENGINE=MyISAM AUTO_INCREMENT=28 DEFAULT CHARSET=cp1250 ROW_FORMAT=FIXED;

-- Dumping data for table urop_degree

/*!40000 ALTER TABLE urop_degree DISABLE KEYS /;
INSERT INTO urop_degree(id,degree,lodge) VALUES
(1,'Sagamor Čikala',1),
(2,'Orlí Sagamor Čikala',1),
(4,'Sagamor',1),
/!40000 ALTER TABLE urop_degree ENABLE KEYS */;

origin data:
INSERT INTO urop_degree VALUES ('Sagamor Čikala', 5, 2, 'ml_sagamor_cikala.gif', 1, 6, 0, 6, 0, 6, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 'Je ten, kdo je starý 14 let (hranice může být náčelníkem kmene snížena).');
INSERT INTO urop_degree VALUES ('Orlí Sagamor Čikala', 6, 2, 'ml_orli_sagamor_cikala.gif', 1, 6, 0, 6, 0, 6, 0, 6, 0, 12, 0, 0, 0, 0, 0, 0, NULL);
INSERT INTO urop_degree VALUES ('Sagamor', 3, 1, 'vl_sagamor.gif', 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, NULL);

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.