I have been doing backup of MySQL tables using MySqlBackup.dll in C#. I have no idea on how to backup specific table inside a MySQL schema. How can I backup only one or two specific tables using C#?
According to this documentation section, you can specify it in the MySqlBackup.ExportInfo using the List<string> property called TablesToBeExportedList.
So, something like this should work:
string constring = "server=localhost;user=root;pwd=1234;database=test1;";
string file = "Y:\\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.ExportInfo.TablesToBeExportedList = new List<string> {
"Table1",
"Table2"
};
mb.ExportToFile(file);
}
}
}
Related
I built a windows form application using c# as a programming language and MySQL as DBMS, I want to add a button for exporting database when user click it.
What I created so far is :
MySqlCommand cmd = new MySqlCommand("SELECT * FROM client INTO OUTFILE '"+path+"' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY'\\n' ", con);
MySqlDataReader dataReader = cmd.ExecuteReader();
dataReader.Read();
But the problem is that this code export data only NOT schema of tables. Is there is any way to export database with schema by SQL statement.
You can use MySqlBackup.NET
https://github.com/MySqlBackupNET/MySqlBackup.Net
Sample codes:
Backup a MySQL database
using MySql.Data.MySqlClient;
then the code,
private void Backup()
{
string constring = "server=localhost;user=root;pwd=qwerty;database=test;";
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();
}
}
}
}
Restore a MySQL database
private void Restore()
{
string constring = "server=localhost;user=root;pwd=qwerty;database=test;";
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();
}
}
}
}
I use Visual Studio community 2015 and i use MySQL connector (MySQL for Visual Studio) for connection my MySQL database to Visual Studio, this part is already done and i have Visual Studio connected to database.
Now i like to know what is my next step to get (using a select query) data from the database to my form program ?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Test_1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// How can i get data from the database in here ?
}
}
}
I got my answer ! Check best answer.
I've gotta run for a bit so I'll take you at yoyur word that you've tried something and post this in hopes it may help you (it's nice to see what you've done to know how to help you).
You said you had the connection working. Here's some examples of basic queries. The most important thing to remember is there's a lot of different ways to do this, so these are just intended as examples. They are all manual -- for help databinding omething automatically, you'll have to post and ask.
Please PLEASE as you learn to do this - make SURE you always use parameters and don't do things like "UPDATE myUserData set DRIVER_LICENSE = 'U7439821' WHERE LAST_NAME = 'Smith'". You are begging for bad things to happen to you if you do that. Take the extra 30 seconds to use command.Parameter.Add(,).
Finally, these examples are for MS-SQL Server. You'll need to change the connection from SqlConnection to MySqlConnection and from SQLCommand to MySqlCommand.
If you have any other questions, just ask.
//these are connection methods that help connect you to your database manually.
public SqlConnection getConn()
{
return new SqlConnection(getConnString());
}
public string getConnString()
{
return #"Data Source=lily.arvixe.com;Initial Catalog={My_Database_Name};Persist Security Info=True;User ID={My_Database_Username};Password={My_Database_Password};Connection Timeout=7000";
}
//to get a single value from a single field:
public object scalar(string sql)
{
object ret;
using (SqlConnection conn = getConn())
{
conn.Open();
using (SqlCommand com = conn.CreateCommand())
{
com.CommandText = sql;
ret = com.ExecuteScalar();
}
conn.Close();
}
return ret;
}
//To do a SELECT with multiple rows returned
private List<string> get_Column_Names(string tableName)
{
List<string> ret = new List<string>();
using (SqlConnection conn = getConn())
{
conn.Open();
using(SqlCommand com = conn.CreateCommand())
{
com.CommandText = "select column_Name from INFORMATION_SCHEMA.COLUMNS where table_Name = '" + tableName + "'";
com.CommandTimeout = 600;
SqlDataReader read = com.ExecuteReader();
while (read.Read())
{
ret.Add(Convert.ToString(read[0]));
}
}
conn.Close();
}
return ret;
}
// to do an INSERT or UPDATE or anything that does not return data
// USE PARAMETERS if people go anywhere near this data
public void nonQuery(string sql)
{
using(SqlConnection conn = getConn())
{
conn.Open();
using(SqlCommand com = conn.CreateCommand())
{
com.CommandText = sql;
com.CommandTimeout = 5900;
com.ExecuteNonQuery();
}
conn.Close();
}
}
//to save a DataTable manually:
public void saveDataTable(string tableName, DataTable table)
{
using (SqlConnection conn = getConn())
{
conn.Open();
using (var bulkCopy = new SqlBulkCopy(conn))//, SqlBulkCopyOptions.KeepIdentity))
{
// my DataTable column names match my SQL Column names, so I simply made this loop. However if your column names don't match, just pass in which datatable name matches the SQL column name in Column Mappings
foreach (DataColumn col in table.Columns)
{
bulkCopy.ColumnMappings.Add(col.ColumnName, "[" + col.ColumnName + "]");
}
bulkCopy.BulkCopyTimeout = 8000;
bulkCopy.DestinationTableName = tableName;
bulkCopy.BatchSize = 10000;
bulkCopy.EnableStreaming = true;
// bulkCopy.SqlRowsCopied += BulkCopy_SqlRowsCopied;
//bulkCopy.NotifyAfter = 10000;
//isCopyInProgess = true;
bulkCopy.WriteToServer(table);
}
conn.Close();
}
}
Again, there are more than a few ways to accomplish each of these tasks programatically - I'm just showing you the most basic. If you want to learn how to automatically bind a control to data, try searching for "C-sharp Databind CONTROL_NAME Visual studio" and you should get all the help you need.
I got my answer :
MySqlConnection sqlConnection1 = new MySqlConnection("server=server;uid=username;" + "pwd=password;database=database;");
MySqlCommand cmd = new MySqlCommand();
MySqlDataReader reader;
cmd.CommandText = "SELECT * FROM table";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
try
{
reader.Read();
value = reader.GetString(x);
}
finally
{
reader.Close();
}
I'm trying to get data from a SQL Server local database. I have created Table with 1 columns buyEURrate type float and the table name is CurrencyRates I have global double variable and I'm trying to set its value the same as the first Row from the buyEURrate columns in CurrencyRates on FormLoad so this code below is inside FormLoad. I'm really new to SQL with C#.
I'm using Visual Studio 2012 and the this is Windows Forms App
using (SqlCeConnection conn =
new SqlCeConnection(#"Data Source=C:\Users\FluksikartoN\Documents\Visual Studio 2012\Projects\BuroFoki\BuroFoki\MainDB.sdf"))
using (SqlCeCommand cmd = conn.CreateCommand())
{
conn.Open();
//commands represent a query or a stored procedure
cmd.CommandText = "SELECT buyEURrate FROM CurrencyRates";
using (SqlCeDataReader rd = cmd.ExecuteReader())
{
while (rd.Read())
{
EURbuy = Convert.ToDouble(rd[0]);
EURsell = Convert.ToDouble(rd[1]);
//Index was outside the bounds of the array. error
}Table
}
conn.Close();
}
SOmething like this should work:
using (SqlCeConnection conn =
new SqlCeConnection(#"Data Source=C:\Users\FluksikartoN\Documents\Visual Studio 2012\Projects\BuroFoki\BuroFoki\MainDB.sdf"))
using (SqlCeCommand cmd = conn.CreateCommand())
{
conn.Open();
//commands represent a query or a stored procedure
cmd.CommandText = "SELECT buyEURrate FROM CurrencyRates";
using (SqlCeDataReader rd = cmd.ExecuteReader())
{
while(rd.Read())
{
double variable = Convert.ToDouble(rd[0]);
string foo = rd.GetString[1];
//do something with variable and foo before going to next row in query
}
}
conn.Close();
}
This may also work
double variable = rd.GetDouble(0);
Although I'm not 100% sure GetDouble is an actual function like GetString() is
Edit
After double checking double variable = rd.GetDouble(0) will work to pull the first column data as a double
using (SqlCeConnection conn = new SqlCeConnection ("Server=.;Database=Northwind;User Id=sa;Password=as"))
{
using (SqlCeCommand cmd = conn.CreateCommand())
{
conn.Open();
//commands represent a query or a stored procedure
cmd.CommandText = "SELECT buyEURrate FROM CurrencyRates";
using (SqlCeDataReader rd = cmd.ExecuteReader())
{
double rate = 0;
if (rd.Read()) // if datareader has rows
{
rate = Convert.ToDouble(rd[0]);
}
}
conn.Close();
}
}
Try this:
using (SqlCeConnection conn =
new SqlCeConnection(#"Data Source=C:\Users\FluksikartoN\Documents\Visual Studio 2012\Projects\BuroFoki\BuroFoki\MainDB.sdf"))
using (SqlCeCommand cmd = conn.CreateCommand())
{
conn.Open();
//commands represent a query or a stored procedure
cmd.CommandText = "SELECT buyEURrate FROM CurrencyRates";
using (SqlCeDataReader rd = cmd.ExecuteReader())
{
if(rd.Read())
{
double variable = rd.GetDouble(0);
}
}
conn.Close();
}
You first need to Read a tuple using DataReader, if it returns true, you can go ahead and read get actual data.
You can also use cmd.ExecuteScalar() method if you are pretty sure that you want to read exactly first column of the first tuple of your table.
Here's more info at MSDN
I have a MySql database and one of the fields is a GEOMETRY field. I am using ADO.Net to connect to the database and I am writing data into the field like this:
var myGeometry = new MySql.Data.Types.MySqlGeometry(15.3f, 12.9f);
string cmdString = "INSERT INTO `MyTable` (LaunchPoint) VALUES (#val1);";
using (var connection = new MySqlConnection(_connectionString))
{
using (var command = new MySqlCommand())
{
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = cmdString;
command.Parameters.Add(new MySqlParameters("#val1", MySqlDbType.Geometry) {Value = myGeometry});
connection.Open();
command.ExecuteScalar();
}
}
This is working fine. It writes the data to the database and if I do a SELECT command from MySQL Workbench, I can see the data is there.
The problem I am running into is reading the data back. The data comes back as a byte[] instead of a MySqlGeometry object. Here is my read code:
string sql = "SELECT * FROM MyTable";
using (var connection = new MySqlConnection(_connectionString))
{
using (var command = new MySqlCommand())
{
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandTet = sql;
connection.Open();
using (var adapter = new MySqlDataAdapter())
{
using (var ds = new DataSet())
{
adapter.SelectCommand = command;
adapter.Fill(ds);
// Error occurs on the next line
var geo = (MySqlGeometry) ds.Tables[0].Rows[0]["LaunchPoint"];
}
}
}
}
An error occurs when I try to load the geo variable with the data. The error is telling me it can't cast a byte array into a MySqlGeometry. Upon closer look, it does, indeed, seem like the MySQL .NET connector is converting it into a byte array for some reason. I found a similar question about this here. However, this question has no response and it's like 6 years old. Surely this would have been fixed by now if its a bug.
Does anyone have a workaround for this?
Rather than cast, new up a new instance of the object using the byte array constructor.
public MySqlGeometry(MySqlDbType type, byte[] val)
source
var geo = new MySqlGeometry(MySqlDbType.Geometry, ds.Tables[0].Rows[0]["LaunchPoint"]);
I have an ODBC connection to a database and I would like the user to be able to view data within any table. As this is an ASP.net application I cannot trust that the table name sent doesn't also contain nasties. I have tried using a parameterised query but I always get an error saying that I "Must declare the table variable" - this appears to be an issue because it is the table name
string sql = "SELECT TOP 10 * FROM ? ";
OdbcCommand command = new OdbcCommand(sql, dbConnection);
command.Parameters.Add(new OdbcParameter("#table", tableName));
OdbcDataAdapter adapter = new OdbcDataAdapter();
adapter.SelectCommand = command;
adapter.Fill(tableData);
What is the best method to achieve this in a secure way?
Use a stored procedure, it's the safest way.
Some hints:
You probably may also use the System.Data.SqlClient namespace objects
Enclose your connection, command and adapter objects initializations in using statements
Here's a simple example:
string sqlStoredProcedure = "SelectFromTable";
using (OdbcConnection dbConnection = new OdbcConnection(dbConnectionString))
{
dbConnection.Open();
using (OdbcCommand command = new OdbcCommand(sqlStoredProcedure, dbConnection))
{
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.Add(new OdbcParameter("#table", tableName));
using (OdbcDataAdapter adapter = new OdbcDataAdapter(command))
{
adapter.SelectCommand = command;
adapter.Fill(tableData);
}
}
}
Another way to go would be to retrieve all table names and validate the tableName string variable as an entry in the list, maybe using:
DataTable tables = dbConnection.GetSchema(OdbcMetaDataCollectionNames.Tables);
Here's a simple implementation based on your scenario:
string sql = "SELECT TOP 10 * FROM {0}";
using (OdbcConnection dbConnection = new OdbcConnection(dbConnectionString))
{
dbConnection.Open();
DataTable tables = dbConnection.GetSchema(OdbcMetaDataCollectionNames.Tables);
var matches = tables.Select(String.Format("TABLE_NAME = '{0}'", tableName));
//check if table exists
if (matches.Count() > 0)
{
using (OdbcCommand command = new OdbcCommand(String.Format(sql, tableName), dbConnection))
{
using (OdbcDataAdapter adapter = new OdbcDataAdapter(command))
{
adapter.SelectCommand = command;
adapter.Fill(tableData);
}
}
}
else
{
//handle invalid value
}
}