The error message: Access to the path 'C:\backupSALES.sql' is denied.
Here is mycode:
private void BackupSALES()
{
string constring = "server=localhost;user=root;pwd=1234;database=sales;";
string file = "C:\\backupSALES.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); //PROMTS AN ERROR
conn.Close();
}
}
}
}
Related
I am trying to get a select result and write a simple authentication. But i have some problems with reader.HasRows/table.Rows.Count>0, its always false. Maybe reason not in reader/adapter, but i dont have other ideas
Form1.cs[enter image description here][1]
private void button1_Click(object sender, EventArgs e)
{
String loginUser = loginField.Text;
String paswwordUser = passwordField.Text;
DB db = new DB();
DataTable table = new DataTable();
OracleDataAdapter adapter = new OracleDataAdapter();
OracleCommand command = new OracleCommand();
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * from users where login='#uL' AND pass = '#uP' ";
command.Parameters.Add("#uL", OracleDbType.Varchar2).Value = loginUser;
command.Parameters.Add("#uP", OracleDbType.Varchar2).Value = paswwordUser;
command.Connection = db.GetConnection();
db.openConnection();
// OracleDataReader reader = command.ExecuteReader();
adapter.SelectCommand = command;
table.Load(command.ExecuteReader());
adapter.Fill(table);
if (table.Rows.Count>0)
MessageBox.Show("Yes");
else
MessageBox.Show("No");
// reader.Close();
}
DB.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.DataAccess.Client;
{
class DB
{
OracleConnection connection = new OracleConnection("Data Source=****/XEPDB1;User Id=****;Password=****;");
public void openConnection()
{
if (connection.State == System.Data.ConnectionState.Closed)
connection.Open();
}
public void closeConnection()
{
if (connection.State == System.Data.ConnectionState.Open)
connection.Close();
}
public OracleConnection GetConnection()
{
return connection;
}
}
}
https://i.stack.imgur.com/8m5ZZ.jpg
try to use colon:
command.CommandText = "SELECT * from users where login=:uL AND pass = :uP ";
command.Parameters.Add("uL", OracleDbType.Varchar2).Value = loginUser;
command.Parameters.Add("uP", OracleDbType.Varchar2).Value = paswwordUser;
command.Connection = db.GetConnection();
db.openConnection();
DataSet dataSet = new DataSet();
using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
{
dataAdapter.SelectCommand = command;
dataAdapter.Fill(dataSet, "Users");
}
var dataTable= dataSet.Tables["Users"];
this.BindingContext[dataTable].EndCurrentEdit();
if(dataSet.HasChanges(DataRowState.Modified))
{
// do your stuff here
}
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´m asking how to connect two or more tables from an MS Access table into c# Windows forms?.
I get the error, that ue cant find the second table:
public partial class Form1 : Form
{
private OleDbConnection connection = new OleDbConnection();
private OleDbConnection connection2 = new OleDbConnection();
public Form1()
{
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\be\Documents\MitarbeiterDaten2.accdb;
Persist Security Info=False;";
connection2.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\be\Documents\DatenbankAbteilung.accdb;
Persist Security Info=False;";
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select ABTEILUNG from combo";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Abteilung.Items.Add(reader["ABTEILUNG"].ToString());
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
finally
{
connection.Close();
}
Anybody got an solution?
Its just about, how to connect two or more MS Access tables into C# Windows forms.
You can reuse the the objects, and can get data from various tables or databases, as :
private void Form1_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select ABTEILUNG from combo";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Abteilung.Items.Add(reader("ABTEILUNG").ToString());
}
reader.Close(); //' Always Close ther Reader. Don't left it open
connection2.Open();
command.Connection = connection2; //' Reusing Same Command Over New Connection
command.CommandText = "Select Field2 from Table2";
while (reader.Read)
{
if (!(Convert.IsDBNull(reader("Field2")))) //' Checking If Null Value is there
{
Abteilung.Items.Add(reader("Field2").ToString());
}
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
finally
{
connection.Close();
connection2.Close();
}
}
How about using using blocks to take care of the commands and connections and then using DataAdapter to get the job done easily. I use some code like this.
DataSet ds = new DataSet();
using (OleDbConnection con = new OleDbConnection(MDBConnection.ConnectionString))
{
con.Open();
using (OleDbCommand cmd = new OleDbCommand("SELECT Column FROM Table1", con))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
da.Fill(ds);
}
}
using (OleDbCommand cmd = new OleDbCommand("SELECT AnotherColumn FROM Table2", con))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
da.Fill(ds);
}
}
}
return ds;
I am working on an C# application which would use the remote MySQL database located in my website hosted on a Linux server with PHP & MySQL support.
I tried to connect directly to the MySQL database using MySql.Data.MySQLClient Reference, as a result, my program is throwing following exception :
"Unable to connect to any of the specified MySQL hosts."
I searched many tutorials but got no solutions... getting the same error.
Can anybody please tell me how to do this.
Please suggest any online links or tutorials or your own idea.
Please help me.
here's my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace mysq
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string conn = "Server = myserver;database = db ;uid = username ;password = pwd ;";
MySqlConnection con = new MySqlConnection(conn);
con.Open();
if (con.State == ConnectionState.Open)
{
MySqlCommand cmd = new MySqlCommand("Select * from table", con);
DataTable dt = new DataTable();
MySqlDataAdapter ad = new MySqlDataAdapter(cmd);
ad.Fill(dt);
dataGridView1.DataSource = dt;
}
}
catch (Exception)
{
throw;
}
}
}
}
Thanks in advance..
I've written an own class with functions for my mysql-connection.
First of all declare the server connection:
string ServerConnection = "Server=localhost;Port=1234;Database=YourDb;Uid=user;password=pass;"
This is how I select data:
public static void DB_Select(string s, params List<string>[] lists)
{
try
{
using(var conn = new MySqlConnection(ServerConnection))
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
using(var sqlreader = cmd.ExecuteReader())
while (sqlreader.Read())
{
if (sqlreader[0].ToString().Length > 0)
{
for (int i = 0; i < lists.Count(); i++)
{
lists[i].Add(sqlreader[i].ToString());
}
}
else
{
foreach (List<string> save in lists)
{
save.Add("/");
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error while selecting data from database!\nDetails: " + ex);
}
}
The call:
List<string> allRows = new List<string>();
DB_Select("SELECT field1 FROM table1 WHERE 1", allRows);
Notice: For every field you are selecting, you have to pass an own list which will be filled with the output.
For updating your database it would be quite the same function. You just wouldnt have to grad the output. Could look like this:
public static void DB_Update(string s)
{
try
{
using (var conn = new MySqlConnection(ServerConnection))
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
int numRowsUpdated = cmd.ExecuteNonQuery();
if(numRowsUpdated < 0)
{
MessageBox.Show("Warning DB-Contact: Affected_rows < 0!");
}
}
}
catch (Exception ex)
{
MessageBox.Show(String.Format("Updating database failed!\n\nSQL: {0}\n\nERROR: {1}",s,ex.Message));
}
}
You have to provide proper connection string in your program, i am suspecious you are passing proper IP address or hostname of the server where you hosted the database. As a first step try to ping the db server to make sure it is reachable from your machine. If it is reachable try as follows:
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
string conn = "Server =<provide proper ip address >;database = db ;uid = username ;password = pwd ;";
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = myConnectionString;
conn.Open();
More details here : http://dev.mysql.com/doc/connector-net/en/connector-net-programming-connecting-open.html
I found this code online, which connects from C# to an SQL server database.
I wish to do something similar, but I want to connect to an Access 2010 database.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace WindowsFormsApplication1.DAL
{
public class PersonDAL
{
public string ConString =
"Data Source=SOURAV-PC\\SQL_INSTANCE;Initial Catalog=test;Integrated Security=True";
SqlConnection con = new SqlConnection();
DataTable dt = new DataTable();
public DataTable Read()
{
con.ConnectionString = ConString;
if (ConnectionState.Closed == con.State)
con.Open();
SqlCommand cmd = new SqlCommand("select * from Person",con);
try
{
SqlDataReader rd = cmd.ExecuteReader();
dt.Load(rd);
return dt;
}
catch
{
throw;
}
}
public DataTable Read(Int16 Id)
{
con.ConnectionString = ConString;
if (ConnectionState.Closed == con.State)
con.Open();
SqlCommand cmd = new SqlCommand("select * from Person where ID= "+ Id +"", con);
try
{
SqlDataReader rd = cmd.ExecuteReader();
dt.Load(rd);
return dt;
}
catch
{
throw;
}
}
}
}
How should I change my code to do that ?
For the example, let's assume that my access DB is in: C:\VisualStudioProject\Sample
Thank you!
You need to do the following:
Use Connection string as:
string connectionstring = Standard security
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccessFile.accdb;
Persist Security Info=False;
Use OLEDB instead of SQL
OleDbConnection MyConn = new OleDbConnection(connectionstring);
public class PersonDAL
{
public string ConString =
#"Standard security Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccessFile.accdb; Persist Security Info=False;";
OleDbConnection con;
DataTable dt;
public PersonDAL()
{
con = new OleDbConnection();
dt = new DataTable();
}
public DataTable Read()
{
con.ConnectionString = ConString;
if (ConnectionState.Closed == con.State)
con.Open();
OleDbCommand cmd = new OleDbCommand("select * from Person", con);
try
{
OleDbDataReader rd = cmd.ExecuteReader();
dt.Load(rd);
return dt;
}
catch
{
throw;
}
}
public DataTable Read(Int16 Id)
{
con.ConnectionString = ConString;
if (ConnectionState.Closed == con.State)
con.Open();
OleDbCommand cmd = new OleDbCommand("select * from Person where ID= " + Id + "", con);
try
{
OleDbDataReader rd = cmd.ExecuteReader();
dt.Load(rd);
return dt;
}
catch
{
throw;
}
}
}