Backup MS SQL Server database through Java program? - java

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");
}

Related

Connection to remote Mysql database closing

I made a java app on my local machine which is connecting to a remote MySQL database, when I run on localhost it works OK, but on the remote connection after a few seconds without interaction it is losing the connection and brings
No operation allowed after connection closed.
and
com.mysql.jdbc.exceptions.jdbc4.MySQL.NonTransientConnectionException:No operation allowed after connection closed.
I have tried to remove con.close from my code but still the same.
How do I keep the connection alive until I close the app?
private void jButton18ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton18ActionPerformed
// TODO add your handling code here:
String stkidreq = txtserchreq.getText();
String pool = lblpool.getText();
String dform = ((JTextField) jdaterfrom.getDateEditor().getUiComponent()).getText();
String dto = ((JTextField) jdaterto.getDateEditor().getUiComponent()).getText();
String rstatus = cmbstatus.getSelectedItem().toString();
String exdate = ((JTextField) jdaterfrom.getDateEditor().getUiComponent()).getText();
((DefaultTableModel) tblreq.getModel()).setRowCount(0);
DefaultTableModel model = (DefaultTableModel) tblreq.getModel();
try {
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection conn2 = DriverManager.getConnection("jdbc:mysql://so /so n so", "so so", "");
Statement st = conn2.createStatement();
String query = " select r.request_id, r.shareholder_id, s.username, s.shareholder_fname, s.shareholder_lname, s.shareholder_phone, r.request_date, r.request_amount, r.pool, r.notes, r.req_status from requests r, shareholder s, saving_pool p where r.shareholder_id = '" + stkidreq + "' and s.shareholder_id = '" + stkidreq + "' and p.Pool_name = '" + pool + "' and s.pool = '" + pool + "' and s.shareholder_id = r.shareholder_id and (r.request_date between '" + dform + "' and '" + dto + "') and r.req_status = '" + rstatus + "' order by r.request_date asc ";
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
String request_id = rs.getString("request_id");
String shareholder_id = rs.getString("shareholder_id");
String username = rs.getString("username");
String shareholder_fname = rs.getString("shareholder_fname");
String shareholder_lname = rs.getString("shareholder_lname");
String shareholder_phone = rs.getString("shareholder_phone");
String request_date = rs.getString("request_date");
String request_amount = rs.getString("request_amount");
String pool3 = rs.getString("pool");
String notes = rs.getString("request_date");
String req_status = rs.getString("req_status");
model.addRow(new Object[]{request_id, shareholder_id, username, shareholder_fname, shareholder_lname, shareholder_phone, request_date, request_amount, pool3, notes, req_status});
}
rs.close();
st.close();
conn2.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}

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.

Connecting to different schemas using prepared statement

I have the following code running fine with one sql statement selectEmpShowDocs_SQL referring to schema1. In this scenario, I have hard coded the value of empID as 2 as shown in the sql below :
private String selectEmpShowDocs_SQL =
"SELECT " +
"emp_doc " +
"FROM " +
"schema1.emp_info " +
"WHERE " +
"doc_id = ? "+
"AND"+
"empID = 2";
Now, I have another sql statement which is retrieving the emp_id value and instead of hardcoding the value just like I did above for empID, I want to pass the value of emp_id obtained from the following sql statement to the above sql statement. This is the statement which is referring to schema2.
private String selectEmpIDSQL =
"SELECT " +
"emp_id " +
"FROM " +
"schema2.emp_id " +
"WHERE " +
"company_id = 435 "
I am wondering is it possible to connect with two different schemas with one prepared statement? Here someone mentioned that prepared statement is bound to a specific database and in that case if it's not possible, what would be the best approach for me?
Here is the full code that works fine for me using only the SQL query referring to schema1.
public List<EmployeeDocument> getEmployeeDocument(String docId, Integer employeeID) throws DaoException
{
StopWatch stopWatch = new StopWatch();
stopWatch.start();
DataSource ds = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<EmployeeDocument> empShowDocs = new ArrayList<EmployeeDocument>();
try {
ds = jdbcTemplate.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(selectEmpShowDocs_SQL);
logger.debug("sql query :" + selectEmpShowDocs_SQL);
System.out.println(selectEmpShowDocs_SQL);
pstmt.setString(1, docId);
logger.debug("sql parameters, docId:" + docId);
rs = pstmt.executeQuery();
while(rs.next()) {
EmployeeDocument empShowDocRecord = new EmployeeDocument();
empShowDocRecord.setEmp_Content(rs.getString("emp_doc")));
empShowDocs.add(empShowDocRecord);
}
} catch(Throwable th) {
throw new DaoException(th.getMessage(), th);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if (pstmt != null) {
try {
pstmt.close();
} catch(SQLException sqe) {
sqe.printStackTrace();
}
pstmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
conn = null;
}
if (ds != null) {
ds = null;
}
}
return empShowDocs;
}
private String selectEmpShowDocs_SQL =
"SELECT " +
"emp_doc " +
"FROM " +
"schema1.emp_info " +
"WHERE " +
"doc_id = ? "+
"AND"+
"empID = 2";
private String selectEmpIDSQL =
"SELECT " +
"emp_id " +
"FROM " +
"schema2.emp_id " +
"WHERE " +
"company_id = 435 "

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 Backup using java GUI

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

Categories

Resources