how to take backup of mysql remote database using java swing - mysql

How to take backup of myphpadmin remote or online server database using java swing.
This is showing error of connection. What to do for mysqld.exe for backup.
Process p;
try {
Runtime runtime = Runtime.getRuntime();
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
url="jdbc:mysql://188.188.188.188:3306/Datatable";
user="datatable";
password="123";
con=DriverManager.getConnection(url,user,password) ;
p=runtime.exec("mysqldump -datatable -p123 --add-drop-database server -B datatable -r"+path);
// "C:/xampp/mysql/bin/mysqldump.exe -uroot -p --add-drop-database server -B newproject -r"+path);
int processComplete = p.waitFor();
if (processComplete==1) {
jLabel1.setText("Backup Created Succuss");
}else{
jLabel1.setText("Can't Create backup");
}
} catch (Exception e) {
e.printStackTrace();
}
What can i do for backup the database.

Related

Run mysqldump from dotnet runtime error -1073741515

I'm trying to create a backup of my mysql databases using Azure Functions. Everything works fine when I run mysqldump.exe in the terminal (SCM/Kudu) but when I run the exact same command from dotnet using Process.Start, the app exits immediately with exit code -1073741515.
This is how I run the code from the terminal using Kudu. This command is literally the command that is also executed from dotnet because I copied it from the logs:
D:\home\site\wwwroot\mysqldump\win\mysqldump.exe --host=*** --user=*** --password=*** --single-transaction --quick --lock-tables=false --routines --hex-blob --result-file=d:\home\site\temp\697ce5ad-0bba-4de1-b070-7c65283a3941 --verbose ***
Result:
Process exits with exit code 0 and the backup file is created as expected.
This is how I run the command from dotnet:
var mysqlDump = "D:\home\site\wwwroot\mysqldump\win\mysqldump.exe";
var process = new Process();
var startInfo = new ProcessStartInfo
{
FileName = mysqlDump,
Arguments =
$"--host={dbHost} --user={dbUser} --password={dbPassword} --single-transaction --quick --lock-tables=false --routines --hex-blob --result-file={sqlPath}{(mysqlDumpVerbose ? " --verbose" : "")} {message.Database}",
WindowStyle = ProcessWindowStyle.Minimized,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true
};
process.StartInfo = startInfo;
process.EnableRaisingEvents = true;
process.OutputDataReceived += (sender, e) =>
{
if (!string.IsNullOrWhiteSpace(e.Data))
{
log.LogInformation(e.Data);
}
};
process.ErrorDataReceived += (sender, e) =>
{
if (!string.IsNullOrWhiteSpace(e.Data))
{
log.LogError(e.Data);
}
};
try
{
log.LogInformation($"Executing '{startInfo.FileName} {startInfo.Arguments}'...");
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
process.WaitForExit(1000 * 60 * 10);
if (process.ExitCode != 0)
{
throw new ApplicationException(
$"Process did not exit with code 0 (zero). Actual exit code: {process.ExitCode}");
}
}
finally
{
log.LogInformation($"Cleaning up files...");
TryDeleteFile(sqlPath, log);
TryDeleteFile(sqlCleanedPath, log);
TryDeleteFile(zipPath, log);
}
Output:
[Information] Executing 'D:\home\site\wwwroot\mysqldump\win\mysqldump.exe --host=*** --user=*** --password=*** --single-transaction --quick --lock-tables=false --routines --hex-blob --result-file=d:\home\site\temp\697ce5ad-0bba-4de1-b070-7c65283a3941 --verbose ***'...
[Error] Exception: Process did not exit with code 0 (zero). Actual exit code: -1073741515
These are the versions:
mysqldump version: 8.0.23 (8.0.26 and 8.0.27 don't work either)
dotnet runtime: 3.1
Azure functions runtime: 3
I also tried a 5.7.* version of mysqldump which actually starts but then crashes with exit code 2 when it reached a certain table in the database, regardless of how I execute the command.
I really have no clue why the exact same command does work in the terminal but not work from dotnet or why mysqldump version 5.7.35 does start but 8.0.* doesn't. Any ideas anyone?

Unable to connect to MySQL Database with Java through SSH

I know that there are many questions regarding this problem already, and believe me I've looked through all of them.
Some background, I'm using IntelliJ and I've been able to both connect to the database with IntelliJ's data source tool and I've been able to SSH into the server itself using the terminal. For some reason, even if I try to do the same thing with Java it doesn't work. Here's my code:
String serverIP = "123.45.67.890"
String username = "root";
String password = "password";
// Establish SSH tunnel with server if not running locally
try {
if (!Inet4Address.getLocalHost().getHostAddress().equals(ServerIP) {
System.out.println("Remote connection detected.");
System.out.println("Establishing SSH Tunnel...");
JSch jSch = new JSch();
Session session = jSch.getSession(username, ServerIP, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
System.out.printf("Connecting to remote server at %s...\n", ServerIP);
session.connect();
System.out.println("Connected!");
session.setPortForwardingL(3306, ServerIP, 3306);
}
} catch (Exception e) {
e.printStackTrace();
}
// Load mySQL Driver
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
String url = String.format("jdbc:mysql://%s:3306/db_name", ServerIP);
// Connect to database
System.out.println("Connecting to database...");
try (Connection connection = DriverManager.getConnection(url, username, password)) {
System.out.println("Database connected!");
this.connection = connection;
} catch (SQLException e) {
this.connection = null;
throw new IllegalStateException("Cannot connect to database!", e);
}
And here's the error I get:
Remote connection detected.
Establishing SSH Tunnel...
Connecting to remote server at 123.45.67.890...
Connected!
Loading driver...
Driver loaded!
Connecting to database...
java.lang.IllegalStateException: Cannot connect to database!
...
a bunch of crap
...
Caused by: java.sql.SQLException: null, message from server: "Host 'my.personal.computer.local.hostname' is not allowed to connect to this MySQL server"
...
a bunch more crap
...
It seems to me like for some reason, the Java code isn't using the SSH tunnel I put so much effort into copying StackOverflow code to make, and is instead rudely trying to connect normally. What am I doing wrong?
Some more info: The server itself is configured to listen for SQL on 0.0.0.0 and I also set the firewall to accept connections on port 3306.
Edit for clarity: I understand that I can probably fix this by giving my local computer privileges on the server, but I want to be able to connect through SSH.
Solution by OP.
The reason SSH wasn't working was because I needed to use a local open port, connect to SQL through that, then forward that to the remote port 3306. Also, I needed to port forward through localhost, not the server address.
(That is, change the session.setPortForwardingL(3306, ServerIP, 3306); line to session.setPortForwardingL(some-open-port, "localhost", 3306); and "jdbc:mysql://%s:3306/db_name" to "jdbc:mysql://%s:same-open-port/db_name".

Connect to remote mysql host from network with proxy

Ubuntu machine in internet zone with proxy server.
And i want to connect to remote mysql server mysql -u userName -p -h hostname.
And also i have java application that connect to that remote mysql host using hibernate ORM.
And i can't connect with the server.
Edit
I dont want to use mysql proxy but my database exists on remote server but my local machine have connection to the internet throw web proxy so i can't connect to remote db server.
And when i try connect from machine that has direct access to the internet That Work Perfectly
Trials.
1-System -> Preferences -> Network Proxy.
2- export http_proxy = http:userName:password#proxyserver:port
but that doesn't work.
and help will be appreciated..
Update:
static {
// SOCKS Proxy
System.setProperty("proxySet", "true");
System.setProperty("socksProxyHost", "proxy-host");
System.setProperty("socksProxyPort", "proxy-port");
System.setProperty("http.proxyHost", "proxy-host");
System.setProperty("http.proxyPort", "proxy-port");
System.setProperty("java.net.socks.username", "username");
System.setProperty("java.net.socks.password", "password");
Authenticator.setDefault(new ProxyAuthenticator("username", "password"));
// Open Web Site Work good
try {
URL url = new URL("http://www.kooora.com/");
URLConnection con = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
// Read it ...
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
} catch (IOException iOException) {
iOException.printStackTrace();
}
// But open mysql connection throw exception
Class.forName("com.mysql.jdbc.Driver").newInstance();
return DriverManager.getConnection(getDBUrl(), USERNAME, PASSWORD);
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

Grails H2 Database DbConsole - Database backup

I have grails 2.0 which comes with H2 database and dbconsole.
I want to take the database backup from dbconsole:
databse url : "jdbc:mysql://localhost/opal"
Username : root
password: (none)
in the tools section of dbconsole there is a option to backup the database.
it will ask 3 things
Target file name: ~/backup.zip(by default)
Source directory:
Source database name: opal (name of my database)
when i press run , it gives error,
No database files have been found in directory E:/Workspace/opal for the database opal
can anybody suggest how to take the database backup.
I've never gotten that to work. If you just want a snapshot of data for development (load on startup) I found that using DBUnit to export/import the data worked great for me. I wrote a script to export it that I call from the console:
class DataExport {
def ctx = SCH.servletContext.getAttribute(GA.APPLICATION_CONTEXT)
def exportData() {
println "-->export"
def ds = ctx.dataSourceUnproxied
println ds.dump()
Connection jdbcConnection = ctx.dataSourceUnproxied.getConnection()
IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
println connection.dump()
ITableFilter filter = new DatabaseSequenceFilter(connection);
IDataSet dataset = new FilteredDataSet(filter, connection.createDataSet());
FlatXmlDataSet.write(dataset, new File("full.xml").newWriter());
connection.close()
}
}
And then in bootstrap you can load it back in
Connection jdbcConnection
FlatXmlDataSet dataSet = new FlatXmlDataSetBuilder().build(new ClassPathResource('resources/data/full.xml').inputStream)
jdbcConnection = ctx.dataSource.getConnection()
IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
try {
DatabaseOperation.INSERT.execute(connection, dataSet)
} catch(e) {
e.printStackTrace()
throw(e)
} finally {
jdbcConnection.close()
}
log.info 'data loaded'
I think this site would be quite helpful. Or, on taking dump of the database and to restore the database try snippet below:
mysqldump -u root -p my_database Table1 Table2 > /home/user/tablesDump.sql;
and to restore the table(s) back:
mysql -u root -p my_database_2
mysql> source /home/user/tablesDump.sql;
Both tables were created in my_database_2.

connecting to MySQL using JDBC in eclipse

So I want to create a JDBC connection to MySQL server that is installed on my pc, here are the steps,
I installed MySQL with the username and password "root", downloaded mysql-connector-java and from theere I coped the JAR "mysql-connector-java-5.1.12-bin" to "C:\Sun\SDK\jdk\jre\lib\ext", I then added it as an external JAR in my project in eclipse, now in my class I have this code:
public void initialiseDatabase()
{
try {
// Load the Driver class.
Class.forName("com.mysql.jdbc.Driver");
//Create the connection using the static getConnection method
databaseConnection = DriverManager.getConnection (databaseUrl+databaseName,
dbUserName, dbPassword);
sqlStatement = databaseConnection.createStatement();
}
catch (SQLException e) {e.printStackTrace();}
catch (Exception e) {e.printStackTrace();}
}
(this is going to be psuedocode cause I am reading from a properties file and don't want the one helping me reading through long lines of code from main to figure out all the variables),
where databaseUrl = "127.0.0.1"
dbUserName = "root"
dbPassword = "root"
databaseName = "MySQL" //this one I am not sure of, do I need to create it or is it set inherenrly?
now the MySQL server is up and running, but when I call the method initialiseDatabase the following exception is thrown:
"java.sql.SQLException: No suitable driver found for rootroot
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Proxy$JDBCConnection.initialiseDatabase(Proxy.java:721)"
when line 721 is:
sqlStatement = databaseConnection.createStatement();
Where have I gone wrong?
thanks
Your database url should look like this:
jdbc:mysql://host:port/database
Example, if you use localhost, the default port and a database named cachedb, your url would be:
jdbc:mysql://localhost/cachedb