MYSQL Backup using java GUI - java

I am trying to backup my database and this is the code I've written but for some reason it is not backing up?? i am using local host (MAMP) and the operating system I am using is MAC OSX.
public boolean databaseBackup(String dbName, String dbUserName, String dbPassword, String path) {
String qu = "/Applications/MAMP/Library/bin/mysqldump -u" + dbUserName + " -p" + dbPassword + " --database" + dbName + " -r " + path;
System.out.println(qu);
Process runtimeProcess;
Properties pr = new Properties();
pr.setProperty("user", "username");
pr.setProperty("password", "password");
Connection con = null;
PreparedStatement stmt = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:8889/Database", pr);
runtimeProcess = Runtime.getRuntime().exec(qu);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("5");
System.out.println("Backed up");
return true;
} else {
System.out.println("Not Backed up");
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
}
in my jframe form I wrote this:
code.databaseBackup("Database","root", "root", "/Users/dipeshramesh/Dropbox/TeamProject/TeamProject2.sql");
so when a person press backup button it calls code.databaseBackup method and dose its jobs.
if I run this it shows a message "Not Backed up" dose any know this?

use String qu = "/Applications/MAMP/Library/bin/mysqldump -u" + dbUserName + " -p" + dbPassword + " --database" + dbName + " > " + path;
command - /Applications/MAMP/Library/bin/mysqldump -u yourUser -p --opt yourdb > yourdump.sql

Related

How to create Backup of a mysql database in java

I have seen there are many articles on this issue and I tried all of them but I am still fail to create a backup using java.
Here is my code:
public class CreateBackup {
public static void main(String[] args) {
try {
File file = new File("mysqlBackup");
if (!file.isDirectory()) {
file.mkdir();
}
String fileName = "backup_" + new Date().getTime() + ".sql";
String path = file.getAbsolutePath() + "/" + fileName;
String cmd = "/usr/bin/mysqldump -uroot -proot userDb > " + path; //-The root after u is the mysql database user name, and the 123456 followed by - p is the user password. Note that there is no space; dbName fills in the database name that needs to be backed up, and the greater than sign is followed by the generated file path
System.out.println("path " +cmd);
Process runtimeProcess = Runtime.getRuntime().exec(cmd );
int processComplete = runtimeProcess.waitFor();
/*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
if (processComplete == 0) {
System.out.println("Backup Complete");
} else {
System.out.println("Backup Failure");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I tried to run in ubuntu also tried with windows but mentioning mysqldump full path "C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqldump". Why my code is always returning backup failure? Help me, please. Thanks in advance.
I fixed this code by adding more lines. while executing.
File f = new File(file, new Timestamp(System.currentTimeMillis()).getTime() + ".sql");
String path = f.getPath();
String username = "root";
String password = "root";
String dbname = "userDb";
String executeCmd = "/usr/bin/mysqldump -u" + username + " -p" + password
+ " --add-drop-database -B " + dbname + " -r " + path;
Process runtimeProcess;
try {
// System.out.println(executeCmd);//this out put works in mysql shell
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
System.out.println(executeCmd);
// runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
System.out.println("processComplete" + processComplete);
if (processComplete == 0) {
System.out.println("Backup created successfully");
} else {
System.out.println("Could not create the backup");
}
} catch (Exception ex) {
ex.printStackTrace();
}
Hope it will help others..

Error when trying to insert new data into sql databse in java

I am trying to insert new data in a SQL database using a DAO. I have a boolean method for insert but there is a SQL error or database is missing. Database is not missing because I tested it and it displays everything from the table.
Here is the connection method
public Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
String dbURL = "jdbc:sqlite:studentdb.sqlite";
dbConnection = DriverManager.getConnection(dbURL);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
And the insert method
public boolean insertStu(Student stu) throws SQLException {
Connection dbConnection = null;
Statement statement = null;
ResultSet resultset = null;
boolean b = false;
try {
String query = "insert into studentdb (Name, Gender, DOB, Address, Postcode, StudentNumber, CourseTitle, StartDate, Bursary, Email) values (\""
+ stu.getName() + "\"," + "\"" + stu.getGender() + "\"," + "\"" + stu.getDob() + "\"," + "\""
+ stu.getAddress() + "\"," + "\"" + stu.getPostcode() + "\"," + "\"" + stu.getStudentNumber()
+ "\"," + "\"" + stu.getCourseTitle() + "\"," + "\"" + stu.getStartDate() + "\"," + "\""
+ stu.getBursary() + "\"," + "\"" + stu.getEmail() + "\")";
dbConnection = getDBConnection();
statement = dbConnection.createStatement();
b = statement.execute(query);
} catch (SQLException s) {
throw new SQLException("Contact Not Added");
} finally {
if (dbConnection != null) {
dbConnection.close();
}
if (statement != null) {
statement.close();
}
if (resultset != null){
resultset.close();
}
}
return b;
}
I have tried the SQL query in different program where the connection method was Statement type and the insert method was still boolean but now the requirement is to use Connection class. Either way it should work but I don't understand way is not working. The Student object has get and set methods for its variables.
Any help would be much appreciated.

Backup MS SQL Server database through Java program?

My question is simple. There's any possible that I follow the process through to completion.
A command like that
backup database master to disk='\\csd0201wnt29f\backup\master.bak' with stats=1
I mean the stats=1 clause.
The method
public void executar(Backup bkp, String comando) throws Exception {
Connection conexao = ConnectionFactory.connectBase(bkp.getServidor(), bkp.getUsuario(), bkp.getSenha());
PreparedStatement cmd = conexao.prepareCall(comando, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
PreparedStatement cmdQuery = conexao.prepareCall("select ##spid");
ResultSet set = cmdQuery.executeQuery();
int spid=0;
if (set.next()) {
spid=set.getInt(1);
System.out.println("SPID" + set.getInt(1));
}
SQLMonitor s = new SQLMonitor(bkp, spid);
s.start();
cmd.execute();
cmdQuery.close();
cmd.close();
conexao.close();
}
The call
public void RealizaBackup(Backup bkp) throws Exception {
SQLComando cmd = new SQLComando();
System.out.println("backup database " + bkp.getBase() + " to disk='" + bkp.getCaminho() + "\\" + bkp.getBase() + ".bak' with stats=1");
cmd.executar(bkp, "backup database " + bkp.getBase() + " to disk='" + bkp.getCaminho() + "\\" + bkp.getBase() + ".bak' with stats=1");
}

importing data from csv file into access database using java

I need to import csv into access database using java. I tried using the following code
my code:
public static void main (String args[])
{
String dbFileSpec = "C:\\Documents and Settings\\admin\\My Documents\\NetBeansProjects\\AutomateExcelDatabase\\Centre.accdb";
// String accessTableName = "Centre";
String csvDirPath = "C:\\Documents and Settings\\admin\\My Documents\\NetBeansProjects\\AutomateExcelDatabase";
String csvFileName = "myjdbcfile.csv";
try (Connection conn = DriverManager.getConnection(
"jdbc:ucanaccess://" + dbFileSpec
// + ";newdatabaseversion=V2007"
)) {
try
{
String strSQL = "SELECT * INTO " + dbFileSpec + " FROM [Text;HDR=YES;DATABASE=" + csvDirPath + ";].[" + csvFileName + "]";
System.err.println("SQL --> "+strSQL);
PreparedStatement selectPrepSt = conn.prepareStatement(strSQL);
boolean result = selectPrepSt.execute();
System.out.println("result = " + result);
}
catch(SQLException ex)
{
System.err.println("Error --->"+ex.toString());
}
conn.commit();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
But it throws error as "net.ucanaccess.jdbc.UcanaccessSQLException: unexpected token: INTO required: FROM".
The two problems with trying to use
SELECT ... INTO NewTableName FROM [Text; ...].[csvFileName]
in this context are:
SELECT ... INTO NewTableName FROM OldTableName is an Access SQL construct that UCanAccess does not support (at least not at the moment), and
... FROM [Text; ...].[csvFileName] is an ODBC "trick" and UCanAccess does not use ODBC.
However, UCanAccess uses HSQLDB and HSQLDB offers support for reading CSV files like so:
final String csvFolder = "C:/__tmp/zzzTest/";
final String csvFileName = "myjdbcfile.csv";
final String csvDbName = "hsqldbTemp";
try (Connection hconn = DriverManager.getConnection(
"jdbc:hsqldb:file:" + csvFolder + "/" + csvDbName,
"SA",
"")) {
try (Statement s = hconn.createStatement()) {
s.executeUpdate("CREATE TEXT TABLE fromcsv (id int, textcol varchar(50))");
s.executeUpdate("SET TABLE fromcsv SOURCE \"" + csvFileName + "\" DESC");
try (ResultSet rs = s.executeQuery("SELECT * FROM fromcsv")) {
while (rs.next()) {
System.out.println(rs.getString("textcol"));
}
}
s.executeUpdate("SHUTDOWN");
File f = null;
f = new File(csvFolder + "/" + csvDbName + ".properties");
f.delete();
f = new File(csvFolder + "/" + csvDbName + ".script");
f.delete();
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
so you could use two connections,
one jdbc:ucanaccess connection to the Access database, and
another jdbc:hsqldb connection to the CSV file,
and then insert the rows from the CSV file into a table in the Access database.
You have mis-typed the query here,
String strSQL = "SELECT * INTO " + dbFileSpec + " FROM
[Text;HDR=YES;DATABASE=" + csvDirPath + ";].[" + csvFileName + "]";
should be ,
String strSQL = "SELECT *" + dbFileSpec + " FROM [Text;HDR=YES;DATABASE=" + csvDirPath + ";].[" + csvFileName + "]";

MySQL export with Java doesn't work

This is the code I created for exporting the database. The problem is, the file is not exported, and the code shows no error message.
public boolean exportDatabase(String fromServer,
String FileName,
String FilePath,
int ExportOpions) {
try {
String dbName ="NMSAzzist";
String dbUser = "root";
String dbPass ="root";
String dumbPath = "C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\";
String executeCmd = dumbPath+"mysqldump -u "+dbUser+ "-p"+dbPass+" "+dbName+ "-r "+FilePath+ "";
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 1) { // if values equal 1 process failed
JOptionPane.showMessageDialog(null, "Backup Failed");//display message
} else if (processComplete == 0) {
JOptionPane.showMessageDialog(null, "\n Backup created Successfully..");
// display message
}
return true;
} catch (final Exception ex) {
NmsLogger.writeErrorLog("Database Connection Failed ", ex.toString());
NmsLogger.writeDebugLog(ex);
return false;
}
How can I export the database to a path specified in the variable FilePath in the name FileName? How can I solve the issue?
And BTW, can i use the following to import the same??
String[] executeCmd = new String[]{"mysql", databaseName, "-u" + userName, "-p" + password, "-e" + FileName };
You first try your executeCmd can run successfullly in db.
In your executeCmd is syntax error. Your code left file name in execution command in
String executeCmd = "/" + dumbPath + "mysqldump -u " + dbUser
+ " -p" + dbPass + " " + dbName + " -r " + FilePath + "\\"
+ FileName;
Check the manual
This works for me.
public class exportDataBase {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
exportDatabase("", "Sma_test.sql", "C:", 0);
}
public static boolean exportDatabase(String fromServer, String FileName,
String FilePath, int ExportOpions) {
try {
String dbName = "dmsdev";
String dbUser = "root";
String dbPass = "root";
String dumbPath = "C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\";
String executeCmd = "/" + dumbPath + "mysqldump -u " + dbUser
+ " -p" + dbPass + " " + dbName + " -r " + FilePath + "\\"
+ FileName;
System.out.println(executeCmd);
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
System.out.println("processComplete: " + processComplete);
if (processComplete == 1) {// if values equal 1 process failed
System.out.println("Backup failed");
}
else if (processComplete == 0) {
System.out.println("Backup Success");
}
return true;
} catch (final Exception ex) {
System.out.println("Connection failed");
return false;
}
}
}
Didn't you forget the Filename?
String executeCmd =dumbPath+"mysqldump -u "+dbUser+ "-p"+dbPass+" "+dbName+ "-r "+FilePath+"\\"+Filename"";
Make it as :
// you did not give file name.
String executeCmd = "cmd " + dumbPath+"mysqldump -u "+dbUser+ "-p"+dbPass+" "+dbName+ "-r "+FilePath+ "\\" + filename;
// I tried running I am getting error code 13.
I think you should make :
if(processComplete != 0) {
//error with error code
} else {
//success
}
instead of
if (processComplete == 1) {// if values equal 1 process failed
System.out.println("Backup failed");
}
else if (processComplete == 0) {
System.out.println("Backup Success");
}
because error-code returned may be other than 0 and 1.
Suggestion : Use Apache Commons exec API, this is more sophisticated than Runtime.exec.

Categories

Resources