MySql Database import is not working with java web application - java

I want to import mysql database using java on web application but unfortunately the mysql.exe process get stuck and next Line of code does not get executed which make browser to keep on loading.
restore.xhtml
<h:panelGrid columns="1" style="margin: 0 auto;">
<p:commandButton value="1 click restore"
action="#restoreBean.oneClickRestore()}" update="all,g" ajax="false"/>
</h:panelGrid>
RestoreBean.java
String absPath ="C:/Users/sms/build/web/resources/backup/backuproot.sql";
String[] executeCmd = new String[]{"mysql ", dbName, "-u " + dbUser, "-p " + dbPwd, "-e ", " \"source "+ absPath+" \""};
try{
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();// after this line no line of code get executed; in taskmanager u can see mysql.exe
if (processComplete == 0) {
restoreMsg = "Successfully restored from SQL : " + absPath;
} else {
restoreMsg = "Error at restoring";
}
} catch (InterruptedException ex) {
Logger.getLogger(RestoreBean.class.getName()).log(Level.SEVERE, null, ex);
}
But the same code runs well and database get imported when used in console application
RestoreDbTest.java
public class RestoreDbTest{
public static void main(String[] args) {
RestoreDbTest b = new RestoreDbTest();
b.restoreDatabase("root", "", "b.sql");
}
public boolean restoreDatabase(String dbUserName, String dbPassword, String source) {
String[] executeCmd = new String[]{"mysql ", dbName, "-u " + dbUser, "-p " + dbPwd, "-e ", " \"source b.sql \""};
Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
// log.info("Backup restored successfully with " + source);
return true;
} else {
//log.info("Could not restore the backup " + source);
}
} catch (Exception ex) {
System.out.println(ex.getCause());
}
return false;
}
}
mysql process list

Related

How to Execute Batch File Remotely in java?

I have to execute batch file present at remote machine from my local machine.
I am connecting through ftp to remote machine and try to execute batch file remotely.but not able to do that also not getiing any exception .below is my code
public static void main(String[] args) throws SocketException, IOException,
InterruptedException {
static String server = "192.168.2.133";
static int port = 21;
static String user = "kamal";
static String pass = "12345";
static FTPClient ftpClient;
// TODO Auto-generated method stub
ftpClient = new FTPClient();
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory("/");
System.out.println(ftpClient.isConnected());
// ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
System.out.println("ftpClient.printWorkingDirectory() "
+ ftpClient.printWorkingDirectory());
String[] str = ftpClient.listNames(ftpClient.printWorkingDirectory());
for (String string : str) {
System.out.println(string);
}
// ftpClient.changeWorkingDirectory(ftpClient.printWorkingDirectory().concat("demo"));
System.out.println("ftpClient.printWorkingDirectory() "
+ ftpClient.printWorkingDirectory());
String psCommand = "C:/Users/kamlesh.kumar/Downloads/PSTools/PsExec.exe //"
+ server + " -u " + user + " -p " + pass;
psCommand = psCommand + " " + "MEF.bat";
// psCommand = psCommand + " " + commandToRunOnRemoteMachine + " " +
// parameters;
String[] cmd = new String[5];
cmd[0] = "cmd.exe";
cmd[1] = "/C";
cmd[2] = psCommand;
cmd[3] = "";
cmd[4] = "";
// Run remote command
// ftpClient.changeWorkingDirectory(ftpClient.printWorkingDirectory().concat("\\\\192.168.2.135\\demo\\demo"));
// System.out.println(ftpClient.printWorkingDirectory());
File f = new File(ftpClient.printWorkingDirectory());
Process p = null;
try {
p = Runtime.getRuntime().exec(cmd, null, f);
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
int exitStatus = 0;
try {
exitStatus = p.waitFor();
System.out.println("exitStatus in try " + exitStatus);
} catch (Exception e) {
System.out.println("exitStatus" + exitStatus);
System.out.println(e.toString());
e.printStackTrace();
} finally {
System.out.println("exitStatus in finally " + exitStatus);
}
if (exitStatus == 0) {
System.out.println("Done");
}
}
You can get PSEXEC from https://technet.microsoft.com/en-us/sysinternals/pxexec.aspx and what I have done before was make a batch file that would copy the file you want ran on the remote pc to that PC then use PSEXEC to execute it remotly and also delete that file that was made. I do not know if that is what you're looking for but it might be sufficient.
set remotecpu="computer you're sending it to"
robocopy "localpcdrive\location1\scripts\script you want ran" \\%remotecpu%\c$\temp_folder
psexec \\%remotecpu% -u "username" -p "password" -i -d "C:\temp_folder\path to\script you want ran"
And if I am not mistaken that will execute the file for you then just do a del command and remove the temp_folder your script is under. Or use something fancy like
If Exist "%SystemDrive%\temp_folder" (RD/S/Q "%SystemDrive%\temp_folder")

statement.executeQuery returning resultset with no rows

My problem is that when I fire a query directly into Oracle, it returns me the rows with proper data. But when I try to fire the same query via Statement, its fetching me a resultset with no rows.
My code is as follows :
public void sendSMStoMobile() {
if (smsGatewayStatus.equals("STOPPED")) {
stringBuilder.append("The control is returning" + "\n");
jTextArea1.setText(stringBuilder.toString());
return;
}
DBCP dbcp = DBCP.getInstance(database_url, username, password);
Connection connection = null;
Statement statement = null;
try {
connection = dbcp.getConnection();
statement = connection.createStatement();
} catch (SQLException ex) {
Logger.getLogger(Send_SMS_Form.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Message : " + ex.getMessage());
} catch (InterruptedException ex) {
Logger.getLogger(Send_SMS_Form.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Message : " + ex.getMessage());
}
ResultSet resultSet = null;
try {
sql = new StringBuffer();
sql.append("SELECT SMS_ID, MOBILE_NO, SMS_CONTENT ");
sql.append("FROM SMSDATA.SMS_DATA ");
//sql.append("WHERE SENT_STATUS = 'N' AND Message_Code IN('LOANREPAY') " );
//sql.append("WHERE SENT_STATUS = 'N' AND Message_Code IN('SPECIAL') " );
sql.append("WHERE SENT_STATUS = 'N' ");
//sql.append("WHERE tranum <= (select max(tranum) -25 from smsgtway.sms_all_tran where SENT_STATUS = 'N' AND Message_Code IN('MEMDEP','MEMGRANT','SAMGRANT')) and SENT_STATUS = 'N' AND Message_Code IN('MEMDEP','MEMGRANT','SAMGRANT') " );
sql.append("ORDER BY SMS_ID desc ");
// sql.append("ORDER BY SENT_TIMSTAMP " );
// For Test
//sql.append("SELECT customer_Code,MOBILE_NO, SMS_CONTENT,SMS_ID " );
//sql.append("FROM MB_SMS_DTL ");
//sql.append("WHERE SENT_STATUS = 'N' ");
//sql.append("ORDER BY SMS_ID " );
// End Test
resultSet = statement.executeQuery(sql.toString());
System.out.println("Code comes here");
/* if(!resultSet.next()){
stringBuilder.append("No Data Found" +"\n");
jTextArea1.setText(stringBuilder.toString());
} */
if (!resultSet.next()) {
System.out.println("no data");
} else {
System.out.println("Data Found...");
do {
//statement(s)
} while (resultSet.next());
}
while (resultSet.next()) {
System.out.println("Data Found...");
String smsId = resultSet.getString(1);
String destMobileNo = resultSet.getString(2);
String message = resultSet.getString(3);
OutboundMessage sms = new OutboundMessage(destMobileNo, message);
System.out.println("Code comes here" + smsId);
//System.out.println("sms = " + sms);
try {
Service.getInstance().sendMessage(sms);
} catch (TimeoutException timeoutException) {
System.out.println("1");
stringBuilder.append("Exception : " + timeoutException.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
} catch (GatewayException gatewayException) {
System.out.println("2");
stringBuilder.append("Exception : " + gatewayException.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
} catch (IOException iOException) {
System.out.println("3");
stringBuilder.append("Exception : " + iOException.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
} catch (InterruptedException interruptedException) {
System.out.println("4");
stringBuilder.append("Exception : " + interruptedException.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
} catch (java.lang.StringIndexOutOfBoundsException siobe) {
System.out.println("5");
stringBuilder.append("Exception : " + siobe.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
}
//Update Table After Send Message
String updateQuery = "UPDATE SMSDATA.SMS_DATA SET SENT_STATUS = 'Y', SENT_DATE = sysdate WHERE SMS_ID = " + smsId;
//String updateQuery = "UPDATE MB_SMS_DTL SET SENT_STATUS = 'Y' WHERE SMS_ID = " + tranNumber ;
//System.out.println("Update Query: " + updateQuery);
if (i < 10) {
System.out.print(smsId + ": Y, ");
}
if (i == 10) {
System.out.print(smsId + ": Y, " + "\n");
i = 0;
}
statement.executeUpdate(updateQuery);
connection.commit();
i = i + 1;
}
} catch (Exception e) {
System.out.println("Message: " + e.getMessage());
System.out.println("Cause: " + e.getCause());
stringBuilder.append("Message: " + e.getMessage() + "\n");
stringBuilder.append("Cause: " + e.getCause() + "\n");
jTextArea1.setText(stringBuilder.toString());
e.printStackTrace();
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException ex) {
Logger.getLogger(Send_SMS_Form.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(Send_SMS_Form.class.getName()).log(Level.SEVERE, null, ex);
}
}
dbcp.releaseConnection(connection);
//Service.getInstance().stopService();
}
}
When I call this function , "no data" is printed in Console . The sql is correct . When I run the sql in Toad , I have found 2 rows .
Please help me .

Runtime - exec to dump database using mysqldump JAVA

I'm trying to use mysqldump with java to create a dump for my database.
I've done the code but the condition if(processCompleted == 0) never happens for some reason that I can not understand. And I say this because on the console there is no exception but it always prints
"Error doing dump!"
which leads me to conclude that if(processCompleted == 0) is never meet.
Can someone please explain me what I'm doing wrong here?
public boolean backupDatabase(String path, String whichServer)
{
String cmd;
Process runtimeProcess;
if(whichServer.equalsIgnoreCase("local"))
{
cmd = "mysqldump -u " + getSourceUsername() + " -p" + getSourceServerPassword()
+ " --add-drop-database -B " + getSourceDatabase() + " -r " + path;
}
else if(whichServer.equalsIgnoreCase("remote"))
{
cmd = "mysqldump -u " + getDestinationUsername() + " -p" + getDestinationServerPassword()
+ " --add-drop-database -B " + getDestinationDatabase() + " -r " + path;
}
else
{
System.out.println("Input server incorrect");
return false;
}
try{
String[] cmdArray = new String[]{"C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysqldump.exe", cmd};
System.out.println("Preparing for dump.");
runtimeProcess = Runtime.getRuntime().exec(cmdArray);
int processCompleted = runtimeProcess.waitFor();
if(processCompleted == 0)
{
System.out.println("Dump done!");
return true;
}
else
{
System.out.println("Error doing dump!");
}
} catch(Exception ex)
{
System.out.println("Exception -> " + ex.getMessage());
}
return false;
}
Here's my code using #MadProgrammer suggestion:
public boolean backupDatabase(String path, String whichServer)
{
List<String> args = new ArrayList<String>();
args.add("C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysqldump.exe");
args.add("-u");
args.add(getSourceUsername());
args.add("-p");
args.add(getSourceServerPassword());
args.add("--add-drop-database");
args.add("-B");
args.add(getSourceDatabase());
args.add("-r");
args.add(path);
try{
ProcessBuilder pb = new ProcessBuilder(args);
pb.redirectError();
Process p = pb.start();
InputStream is = p.getInputStream();
int in = -1;
while((in = is.read()) != -1)
{
System.out.println((char) in);
}
int proccessCompleted = p.waitFor();
if(proccessCompleted == 0)
{
System.out.println("Dump done!");
return true;
}
else
{
System.out.println("Error doing dump!");
return false;
}
}
catch(IOException | InterruptedException ex)
{
System.out.println("Exception exportDB -> " + ex.getMessage() + "|" + ex.getLocalizedMessage());
}
return false;
}
PS; where you wrote "//? Is this a single command?" -p is the command for the password and getSourceServerPassword() is the method to get the password.
I suspect because you've separated the cmdArray into only two elements that mysqldump is treating the second array element as a single command line argument.
Also, you've not paying attention to the output of the process which makes it really difficult for your to ascertain what the processing is trying to tell.
You "base" command also includes mysqldump...
"mysqldump -u " + getSourceUsername() + " -p" + getSourceServerPassword()
+ " --add-drop-database -B " + getSourceDatabase() + " -r " + path;
as part of the command, which means you are effectively calling mysqldump mysqldump...
Instead of using a String, place all your commands into some kind of list instead.
Remember, if it's separated by a space on the command line, it's a separate command/element
List<String> args = new ArrayList<String>
args.add("C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysqldump.exe");
//...
args.add("-u");
args.add(getSourceUsername());
args.add("-p" + getSourceServerPassword()); //?? Is this a single command?
args.add("--add-drop-database");
args.add("-B");
args.add(getSourceDatabase());
args.add("-r");
args.add("path);
//...
Then use ProcessBuilder
ProcessBuilder pb = new ProcessBuilder(args);
pb.redirectError();
Process p = pb.start();
InputStream is = p.getInputStream();
int in = -1;
while ((in = is.read()) != -1) {
System.out.print((char)in);
}
int processCompleted = p.waitFor();
Remember, you should never ignore the output from a process, even if you don't care, you should attempt to consume the content from the InputStream as some processes will hang if there output stream is not read.

Restoring a MySQL backup

I wrote the following code to restore MySQL backup ,
public boolean restoreDB(String dbUserName, String dbPassword) {
try {
NewClassx n = new NewClassx();
n.myf(2);
String source = jTextField1.getText();
Process runtimeProcess;
Connection con = CPool.getConnection();
Statement stmt = con.createStatement();
ResultSet res = null;
res = stmt.executeQuery("select ##datadir");
String Mysqlpath = "";
while (res.next()) {
Mysqlpath = res.getString(1);
}
Mysqlpath = Mysqlpath.replace("data", "bin");
CPool.closeConnection(con);
CPool.closeStatement(stmt);
CPool.closeResultSet(res);
// String[] executeCmd = new String[]{Mysqlpath + "\\mysql", "--user=" + dbUserName, " -e", "source " + "\"" + source + "\""};
// String executeCmd = Mysqlpath + "\\mysql - u "+ dbUserName +" -e "+ "\"" + source + "\"";
//mysql - u admin -p admin accounts <
String[] executeCmd = new String[]{Mysqlpath + "\\mysql", " project_db ", " --user=" + dbUserName, " -e", " source "+ " \"" + source + "\""};
// System.out.println(executeCmd);
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
JOptionPane.showInternalMessageDialog(this, "Backup restored successfully");
return true;
} else {
JOptionPane.showInternalMessageDialog(this, "Backup was not restored");
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
on calling the above function , my application freezes without restoring any backup.
you didn't write password in string
add '-p password' after username

java connection pool autocommit

I'm using for the first time the connection pool in java. The application that I'm writing is a web application deployed on oracle glassfish 3.1 and the resource connection pool is handled by it. I set the autocommit to false on my connection object, returned by the javax.sql.DataSource, but in the code the rollback command has no effect at all. All the previous operation of write are committed automatically. Is there any other settings in java code that I have to do to disable autocommit? Or there is some configuration settings that I have to do on glassfish?
The database that I'm using is Oracle 10g.
I post here a part of the code that is giving me problem:
private int importFile(String id, String fileName, String label,
String prosumerId, String districtCodes)
throws IOException,
SQLException {
logger.debug("Importing file [" + fileName + "]");
File f = new File(fileName);
BufferedReader br = null;
Calendar cal = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String query = "insert into TB_SDK_USER_FILES values ("
+ id + ", '" + label + "', '"
+ fileName.substring(fileName.lastIndexOf("/") + 1) + "', 'active', "
+ "to_date('" + sdf.format(new Date(cal.getTimeInMillis())) + "', 'dd/mm/yyyy hh24:mi:ss'), "
+ "to_date('" + sdf.format(new Date(cal.getTimeInMillis())) + "', 'dd/mm/yyyy hh24:mi:ss'), "
+ "'" + prosumerId + "'"
+ ") ";
logger.debug("Executing query [" + query + "]");
dbl.openDBConnection();
int x = dbl.set(query);
if (x <= 0) {
dbl.rollback();
dbl.closeDBConnection();
logger.error("Insert in TB_SDK_USER_FILES failed, stopping execution ");
return -3;
}
PreparedStatement ps = null;
String line = new String();
try {
br = new BufferedReader(new FileReader(f));
query = "insert into TB_SDK_CONTENTS "
+ "(id, contentCode, cli, content, contentType, PROSUMERID, cld, email) "
+ "values (?,?,?,?,?,?,?,?)";
logger.debug("Executing query [" + query + "]");
ps = dbl.getPreparedStatement(query);
while ((line = br.readLine()) != null) {
String[] tmp = line.split("\t");
if (tmp.length < 4) {
logger.debug("Sono presenti erroneamente meno di 4 valori!!!!");
br.close();
f.delete();
dbl.rollback();
ps.close();
dbl.closeDBConnection();
return -2;
}
ps.setInt(1, new Integer(id).intValue());
String test = tmp[0].replace("*", "");
logger.debug("first column: test [" + test + "]");
try {
if (test.length() > 0) {
double testDouble = Double.parseDouble(test);
//int testInt = Integer.parseInt(test);
}
} catch (NumberFormatException nfe) {
logger.error("The first column does not satisfy the format requested. Found [" + tmp[0] + "] -- NumberFormatException");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -6;
}
if (tmp[0].length() > 0) {
ps.setString(2, tmp[0].trim());
} else {
logger.error("The first column does not satisfy the format requested. Found [" + tmp[0] + "] -- length() <= 0");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -6;
}
test = tmp[1].replace("*", "").trim();
logger.debug("second column: test [" + test + "]");
try {
if (test.length() > 0) {
double testDouble = Double.parseDouble(test);
//int testInt = Integer.parseInt(test);
}
} catch (NumberFormatException nfe) {
logger.error("The second column does not satisfy the format requested. Found [" + tmp[1] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -7;
}
if (tmp[1].length() > 0) {
ps.setString(3, tmp[1].trim());
} else {
logger.error("The second column does not satisfy the format requested. Found [" + tmp[1] + "] -- length() <= 0");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -7;
}
logger.debug("third column: tmp[2] [" + tmp[2] + "]");
ps.setString(4, tmp[2]);
if ((tmp[3].length() > 0) && ((tmp[3].compareToIgnoreCase("TTS") == 0)
|| (tmp[3].compareToIgnoreCase("Audio") == 0))) {
ps.setString(5, tmp[3].trim());
logger.debug("fourth column: tmp[3] [" + tmp[3] + "]");
} else {
logger.error("The fourth column does not satisfy the format requested. Found [" + tmp[3] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -10;
}
ps.setString(6, prosumerId);
if (tmp.length > 4) {
tmp[4] = tmp[4].trim();
if ((tmp[4].length() > 0) && (tmp[4].length() <= 12) && (tmp[4].matches("^\\d*$"))) {
boolean ok = false;
logger.debug("Checking district codes...");
String[] codes = districtCodes.split(",");
for (int i = 0; i < codes.length; i++) {
if (tmp[4].startsWith(codes[i].trim())) {
ok = true;
logger.debug("District code found.");
break;
}
}
if (ok) {
ps.setString(7, tmp[4]);
logger.debug("fifth column: tmp[4] [" + tmp[4] + "]");
} else {
logger.error("The fifth column does not satisfy the format requested. Found [" + tmp[4] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -8;
}
} else if (tmp[4].length() == 0) {
ps.setString(7, "-");
logger.debug("fifth column: tmp[4] [-]");
} else {
logger.error("The fifth column does not satisfy the format requested. Found [" + tmp[4] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -8;
}
} else {
ps.setString(7, "-");
}
if (tmp.length == 6) {
tmp[5] = tmp[5].trim();
if ((tmp[5].length() > 0) && (isValidEmailAddress(tmp[5]))) {
ps.setString(8, tmp[5]);
} else if (tmp[5].length() == 0) {
ps.setString(8, "-");
} else {
logger.error("The sixth column does not satisfy the format requested. Found [" + tmp[5] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -9;
}
} else {
ps.setString(8, "-");
}
x = ps.executeUpdate();
if (x <= 0) {
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
//f.delete();
logger.error("Insert in TB_SDK_CONTENTS failed, stopping execution ");
return -3;
}
}
br.close();
//f.delete();
ps.close();
dbl.commit();
dbl.closeDBConnection();
return 0;
} catch (Exception ex) {
logger.error("An exception occured during the import of file [" + fileName + "] for line [" + line + "]", ex);
dbl.rollback();
if (br != null) {
br.close();
}
if (ps != null) {
ps.close();
}
dbl.closeDBConnection();
//f.delete();
return -1;
}
}
On the other class that handle the DB operation:
public int set(String query) {
Statement statement = null;
int ris = -1;
try {
if (connection == null || !connection.isValid(1)) connect();
logger.debug("Opening statement");
statement = connection.createStatement();
ris = statement.executeUpdate(query);
} catch (SQLException ex) {
logger.error("ERROR in execution of [" + query + "] due to: ", ex);
ris = -1;
} finally {
try {
logger.debug("Closing statement");
if (statement != null) {
statement.close();
}
} catch (SQLException ex1) {
logger.error("ERROR cannot close statement.", ex1);
}
}
return ris;
}
The connection open:
public boolean connect() {
if (dataSource != null) {
try {
connection = dataSource.getConnection();
logger.info("Connection open to DB");
return true;
} catch (SQLException ex) {
logger.error("An error occured during request of connection to datasource, due to...", ex);
return false;
}
}
String url;
if (connectionString.length() > 0) {
url = connectionString;
} else {
url = "jdbc:oracle:thin:#" + host + ":" + port + ":" + sid;
}
try {
// create an OracleDataSource
OracleDataSource ods = new OracleDataSource();
// set connection properties
Properties prop = new Properties();
prop.put("user", user);
prop.put("password", pwd);
ods.setConnectionProperties(prop);
ods.setURL(url);
// get the connection
connection = ods.getConnection();
connection.setAutoCommit(false);
((OracleConnection) connection).setDefaultRowPrefetch(10);
logger.info("Connection open to DB");
return true;
} catch (Exception ex) {
logger.info("An exception occured in execution of [connect]. ");
if (dataSource == null) {
logger.error("[" + url + ", " + user + ", " + pwd + "] ERROR in execution of [connect] due to: ", ex);
}
return false;
}
}
dataSource getConnection():
public static Connection getConnection() throws SQLException {
Connection con = dataSource.getConnection();
con.setAutoCommit(false);
return con;
}
The lookup for the data source is done in the Context Listener at context creation.
Edit:
I'm reading again the oracle tutorials about the usage of pooling connection and other links about it: every example the open and close of the connection to the pool is done in the same method. I thought that was just a need to be more simplest to explain all the steps, but I'm wondering if this is not also a need to satisfy the "transaction" at connection pool level. Can anyone confirm me this? Or give me a documentation link where this is well explained? Thank you very much!

Categories