Clean up JDBC
Hi
Is there a way to clean up the jdbc (oracle 10g) from previously left open statements?
Thank u
K
No, because you should always be closing your JDBC resources properly. :^)
- Saish
Similar Messages
-
How to populate the combo boxes that are created dynamically in jsp
Hi,
I am using JSP.
I am creating combo boxes dynamically (based on the num selected by the user). These dynamically created combo boxes need to have A-Z as options (each box) . Now, when the user chooses the option A in any of the combo-boxes,the rest should not have this option. so on..
how do i achieve this.Kindly help.You'll need to use JavaScript...I have a complicated example and a simple example, however, I cannot really understand the complex example but I know how it works. The looping is too complex for me.
First you'll need to populate a server side variable...depending on how often the data is updated you may want this to run each time a new session is created...this example is run each time Tomcat is started and the application context is initialized:
package kms.web;
// Servlet imports
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContext;
// utility imports
import java.util.Map;
// domain imports
import kms.domain.LocationService;
import kms.domain.DeptService;
import kms.domain.PatentService;
* This listenter is used to initialize
* the Maps of Locations, Patents & Depts used to populate
* pulldown lists in JSPs
public class InitializeData implements ServletContextListener {
* This method creates the Maps.
public void contextInitialized(ServletContextEvent sce) {
ServletContext context = sce.getServletContext();
LocationService lServ = new LocationService();
// Create the Maps
Map campuses = lServ.getCampuses();
Map buildings = lServ.getBuildings();
Map floors = lServ.getFloors();
Map locs = lServ.getLocations();
// And store them in the "context" (application) scope
context.setAttribute("campuses", campuses);
context.setAttribute("buildings", buildings);
context.setAttribute("floors", floors);
context.setAttribute("locs", locs);
DeptService dServ = new DeptService();
Map depts = dServ.getDepts();
context.setAttribute("depts", depts);
PatentService pServ = new PatentService();
Map patents = pServ.getPatents();
context.setAttribute("patents", patents);
//I did this one myself
/* CodeService cServ = new CodeService();
Map masterMks = cServ.getCodes();
context.setAttribute("masterMks", masterMks);
* This method is necessary for interface.
public void contextDestroyed(ServletContextEvent sce) {
// I have no clue what the heck this is for???
// Let me know if you do!
}So now we travel into the PatentService method called 'getPatents();' which in turn calls a PatentDAO method
Map patents = pServ.getPatents();
Below is the code for the PatentService object:
package kms.domain;
import kms.util.ObjectNotFoundException;
import java.util.*;
* This object performs a variety of dept services, like retrieving
* a dept object from the database, or creating a new dept object.
public class PatentService {
* The internal Data Access Object used for database CRUD operations.
private PatentDAO patentDAO;
* This constructor creates a Dept Service object.
public PatentService() {
patentDAO = new PatentDAO();
public Map getPatents() {
Map patents = null;
try {
patents = patentDAO.retrieveAll();
// If the dept object does not exist, simply return null
} catch (ObjectNotFoundException onfe) {
patents = null;
return patents;
}It may be useful for you to see the code of the Patent class:
package kms.domain;
/*** This domain object represents a dept.
public class Patent implements java.io.Serializable {
private int codeGgm;
private String name = "";
private String description = "";
private int creator;
private String creationDate = "";
private int used;
* This is the full constructor.
public Patent(int codeGgm, String name, String desc, int creator, String creationDate, int used) {
this.codeGgm = codeGgm;
this.name = name;
this.description = desc;
this.creator = creator;
this.creationDate = creationDate;
this.used = used;
public Patent() { }
public int getCodeGgm() {
return codeGgm;
public void setCodeGgm(int codeGgm) {
this.codeGgm = codeGgm;
public String getName() {
return name;
public void setName(String name) {
this.name = name;
public String getDesc() {
return description;
public void setDesc(String desc) {
this.description = desc;
public int getCreator() {
return creator;
public void setCreator(int creator) {
this.creator = creator;
public String getCreationDate() {
return creationDate;
public void setCreationDate(String creationDate) {
this.creationDate = creationDate;
public int getUsed() {
return used;
public void setUsed(int used){
this.used = used;
}And here is the Database table which stores the Patents:
DESC PATENT:
CODE_GGM NUMBER(3)
NAME VARCHAR2(15)
DESCRIPTION VARCHAR2(250)
CREATOR NUMBER(10)
CREATION_DATE DATE
USED NUMBER(1)
So, we then travel into the code of the PatentDAO to see how the DAO object executes the DB query to get all of the Data we need for the select list:
package kms.domain;
import javax.naming.*;
import javax.sql.*;
import java.util.*;
import java.sql.*;
import kms.util.*;
* This Data Access Object performs database operations on Patent objects.
class PatentDAO {
* This constructor creates a Patent DAO object.
* Keep this package-private, so no other classes have access
PatentDAO() {
* This method returns a Map of all the Dept names
* The key is the Dept id
Map retrieveAll()
throws ObjectNotFoundException {
Connection connection = null;
ResultSet results = null;
// Create the query statement
PreparedStatement query_stmt = null;
try {
// Get a database connection
Context initContext = new InitialContext();
DataSource ds = (DataSource)initContext.lookup("java:/comp/env/jdbc/keymanOracle");
connection = ds.getConnection();
// Create SQL SELECT statement
query_stmt = connection.prepareStatement(RETRIEVE_ALL_NAMES);
results = query_stmt.executeQuery();
int num_of_rows = 0;
Map patents = new TreeMap();
// Iterator over the query results
while ( results.next() ) {
patents.put(new Integer(results.getInt("code_ggm")), results.getString("name"));
if ( patents != null ) {
return patents;
} else {
throw new ObjectNotFoundException("patent");
// Handle any SQL errors
} catch (SQLException se) {
se.printStackTrace();
throw new RuntimeException("A database error occured. " + se.getMessage());
} catch (NamingException se) {
throw new RuntimeException("A JNDI error occured. " + se.getMessage());
// Clean up JDBC resources
} finally {
if ( results != null ) {
try { results.close(); }
catch (SQLException se) { se.printStackTrace(System.err); }
if ( query_stmt != null ) {
try { query_stmt.close(); }
catch (SQLException se) { se.printStackTrace(System.err); }
if ( connection != null ) {
try { connection.close(); }
catch (Exception e) { e.printStackTrace(System.err); }
private static final String RETRIEVE_ALL_NAMES
= "SELECT code_ggm, name FROM patent ";
}Now when you wish to use the 'combo box' (also called select lists), you insert this code into your jsp:
<TR>
<%@ include file="../incl/patent.jsp" %>
</TR>
depending on how your files on your server are organized, the "../incl/patent.jsp"
tells the container to look up one directory from where the main jsp is to find the 'patent.jsp' file in the 'incl' directory.
I need some help creating multi-level select lists with JavaScript:
Can anyone explain this code:
<%@ page import="java.util.*,kms.domain.*" %>
<jsp:useBean id="campuses" scope="application" class="java.util.Map" />
<TR><TD ALIGN='right'>Campus: </TD>
<TD>
<select name="campus" size="1" onChange="redirect(this.options.selectedIndex)">
<option value="0" selected>No Campus</option>
<% LocationService ls = new LocationService();
Iterator c = campuses.keySet().iterator();
Map[] bm = new Map[campuses.size()];
Map[][] fm = new Map[campuses.size()][0];
Map[][][] lm = new Map[campuses.size()][0][0];
int i2 = 0;
int j2 = 0;
int k2 = 0;
int jj = 0;
int kk = 0;
while (c.hasNext()) {
Integer i = (Integer)c.next();
out.print("<OPTION ");
out.print("VALUE='" + i.intValue()+ "'>");
out.print( (String) campuses.get(i) );
out.print("</OPTION>");
bm[i2] = ls.getBuildingsByCampus(i.intValue());
fm[i2] = new Map[bm[i2].size()];
lm[i2] = new Map[bm[i2].size()][];
Iterator b = bm[i2].keySet().iterator();
j2 = 0;
while (b.hasNext()) {
Integer j = (Integer)b.next();
fm[i2][j2] = ls.getFloorsByBuilding(j.intValue());
lm[i2][j2] = new Map[fm[i2][j2].size()];
Iterator f = fm[i2][j2].keySet().iterator();
k2 = 0;
while (f.hasNext()) {
Integer k = (Integer)f.next();
lm[i2][j2][k2] = ls.getLocationsByFloor(k.intValue());
k2++;
kk++;
j2++;
jj++;
i2++;
} %>
</select></TD>
</TR>
<TR><TD ALIGN='right'>Building: </TD>
<TD>
<select name="building" size="1" onChange="redirect1(this.options.selectedIndex)">
<option value="0" selected>No Building</option>
</select></TD>
</TR>
<TR><TD ALIGN='right'>Floor: </TD>
<TD>
<select name="floor" size="1" onChange="redirect2(this.options.selectedIndex)">
<option value="0" selected>No Floor</option>
</select></TD>
</TR>
<TR><TD ALIGN='right'>Room: </TD>
<TD>
<select name="location_id" size="1">
<option value="0" selected>No Room</option>
</select></TD>
</TR>
<script>
var cNum = <%=i2%>
var bNum = <%=jj%>
var fNum = <%=kk%>
var cc = 0
var bb = 0
var ff = 0
var temp=document.isc.building
function redirect(x){
cc = x
for (m=temp.options.length-1;m>0;m--)
temp.options[m]=null
temp.options[0]=new Option("No Building", "0")
if (cc!=0) {
for (i=1;i<=group[cc-1].length;i++){
temp.options=new Option(group[cc-1][i-1].text,group[cc-1][i-1].value)
temp.options[0].selected=true
redirect1(0)
var group=new Array(cNum)
for (i=0; i<cNum; i++) {
group[i]=new Array()
<% for (int i=0; i< bm.length; i++) {
Iterator bldgs = bm[i].keySet().iterator();
int j = 0;
while (bldgs.hasNext()) {
Integer intJ =(Integer) bldgs.next(); %>
group[<%=i%>][<%=j%>] = new Option("<%=bm[i].get(intJ)%>", "<%=intJ%>");
<% j++;
} %>
var group2=new Array(cNum)
for (i=0; i<cNum; i++) {
group2[i] = new Array()
for (j=0; j<=bNum; j++) {
group2[i][j] = new Array()
<% for (int i=0; i< fm.length; i++) {
for (int j=0; j< fm[i].length; j++) {
Iterator flrs = fm[i][j].keySet().iterator();
int k = 0;
while (flrs.hasNext()) {
Integer intK =(Integer) flrs.next(); %>
group2[<%=i%>][<%=j%>][<%=k%>] = new Option("<%=fm[i][j].get(intK)%>", "<%=intK%>");
<% k++;
} %>
var temp1=document.isc.floor
var camp=document.isc.campus.options.selectedIndex
function redirect1(x){
bb = x
for (m=temp1.options.length-1;m>0;m--)
temp1.options[m]=null
temp1.options[0]=new Option("No Floor", "0")
if (cc!=0 && bb!=0) {
for (i=1;i<=group2[cc-1][bb-1].length;i++){
temp1.options[i]=new Option(group2[cc-1][bb-1][i-1].text,group2[cc-1][bb-1][i-1].value)
temp1.options[0].selected=true
redirect2(0)
var group3=new Array(cNum)
for (i=0; i<cNum; i++) {
group3[i] = new Array()
for (j=0; j<=bNum; j++) {
group3[i][j] = new Array()
for (k=0; k<=fNum; k++) {
group3[i][j][k] = new Array()
<% for (int i=0; i< lm.length; i++) {
for (int j=0; j< lm[i].length; j++) {
for (int k=0; k< lm[i][j].length; k++) {
Iterator locs = lm[i][j][k].keySet().iterator();
int m = 0;
while (locs.hasNext()) {
Integer intM =(Integer) locs.next(); %>
group3[<%=i%>][<%=j%>][<%=k%>][<%=m%>] = new Option("<%=lm[i][j][k].get(intM)%>", "<%=intM%>");
<% m++;
} %>
var temp2=document.isc.location_id
function redirect2(x){
ff = x
for (m=temp2.options.length-1;m>0;m--)
temp2.options[m]=null
temp2.options[0]=new Option("No Room", "0")
if (cc!=0 && bb!=0 && ff!=0) {
for (i=1;i<=group3[cc-1][bb-1][ff-1].length;i++){
temp2.options[i]=new Option(group3[cc-1][bb-1][ff-1][i-1].text,group3[cc-1][bb-1][ff-1][i-1].value)
temp2.options[0].selected=true
</script>
This produces a related select list with 4 related lists by outputting JavaScript to the page being served. It works the same way as the first example that I describe but I don't understand the looping...maybe someone could explain how to go from the single select list to a double and/or triple level drill down? -
Using TxDataSource outside a transaction context
I have two questions about using TxDataSource:
- Can I use a TxDataSource outside a transaction? i.e. can I get a connection
from a TxDataSource if there is no active transaction?
- If the answer to the above question is true, do I have to close the connection
after I'm done using it? The data source is defined on a regular connection pool.
ThanksAt 09:54 AM 7/30/2002 -0700, you wrote:Thanks for your answer, as always:-)
.As far as the closing the connection goes, what do I do if I have multiple ejbs participating in
a transaction, and each one uses the connection from the database (the same connection, as they
are all participating in the same transaction)? Does each ejb method (assuming a session ejb with
REQUIRED transactional method) have to do a connection.close() before the method exits? Or in this
case, will the container automatically release the connection back to the pool when the
transaction commits or rollsback?We have you covered. Any time your code gets a connection from a TxDataSource in the context of
a transactional EJB, or in a servlet with an ongoing UserTransaction, we will cheerfully ignore if
your
code calls commit() or close(), because our Tx coordinator is the only one who knows when to commit.
Closing the connection is irrelevant to the flow either, because even though several EJBs in a given
transaction
all ask for a connection, and all get their own Connection object, these objects are wrappers around
a single
real pool connection, and if you close one wrapper, we know not to do anything with the underlying
pool
connection.
In summary, if you always stick to the basic standard of clean safe JDBC code, it will always
work,
and it is important to do so in a non-transactional state:
myJdbcMethodsLookLike()
Connection c = null;
try {
c = getConnection();
do all the JDBC
c.close();
c = null;
catch (Exception e) {
do whatever
finally {
if (c != null) try {c.close();} catch (Exception ignore){} -
Need help w corba/jdbc class
hi
i'm trying to get this class to work right, i don't think i'm coding it the right way, especially the getAllAccounts() and selectAccounts() methods. this code compiles cleanly, but i get runtime exceptions when i try to run my app. my runtime exceptions look like
############################ StackTrace ############################
java.lang.NullPointerException
at com.kafein.accountServices.AccountServiceImpl.getAllAccounts(AccountS
erviceImpl.java:218)
at com.kafein.idl.accountServices.AccountServicePOA._invoke(AccountServi
cePOA.java:74)
at org.jacorb.poa.RequestProcessor.invokeOperation(RequestProcessor.java
:247)
at org.jacorb.poa.RequestProcessor.process(RequestProcessor.java:477)
at org.jacorb.poa.RequestProcessor.run(RequestProcessor.java:604)
and
Creating 100 Accounts
org.omg.CORBA.UNKNOWN: This exception was reported by the server, it is only re-
thrown here. vmcid: 0x0 minor code: 0 completed: No
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Sou
rce)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.jacorb.orb.SystemExceptionHelper.read(SystemExceptionHelper.java:
157)
at org.jacorb.orb.connection.ReplyInputStream.checkExceptions(ReplyInput
Stream.java:117)
at org.jacorb.orb.Delegate.invoke(Delegate.java:942)
at org.omg.CORBA.portable.ObjectImpl._invoke(Unknown Source)
at com.kafein.idl.accountServices._AccountServiceStub.getAllAccounts(_Ac
countServiceStub.java:134)
at com.kafein.client.AccountClient.main(AccountClient.java:111)
org.omg.CORBA.UNKNOWN: This exception was reported by the server, it is only re-
thrown here. vmcid: 0x0 minor code: 0 completed: No
ORB shutting down...
code for this class is below...
// AccountServiceImpl.java: The AccountService Implementation
package com.kafein.accountServices;
import java.util.Hashtable;
import java.util.Calendar;
import java.util.GregorianCalendar;
import junit.framework.TestCase;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.omg.PortableServer.*;
import com.kafein.idl.accountServices.AccountServicePOA;
import com.kafein.idl.accountServices.AccountEntryStruct;
import com.kafein.idl.accountServices.AccountStruct;
import com.kafein.idl.utilities.DateTimeStruct;
import com.kafein.idl.exceptions.NotFoundException;
import com.kafein.idl.exceptions.DataValidationException;
import com.kafein.idl.errorCodes.DataValidationErrorCodes;
import com.kafein.utils.ServiceHandler;
import com.kafein.utils.Log;
import java.net.URL;
import java.sql.*;
import java.util.*;
* AccountServiceImpl is an implementation of the
* idl.accountServices.AccountService interface.
public class AccountServiceImpl extends AccountServicePOA {
POA poa;
private Hashtable accounts = new Hashtable(); // collection of Accounts
private static int nextAccountID = 1; // global account ID
Connection connection;
Vector connections;
Statement statement;
PreparedStatement preparedStatement;
* Construct an instance.
public AccountServiceImpl(POA aPOA, String driver, String url, String user, String password) {
super();
poa = aPOA;
driver = driver;
url = url;
user = user;
password = password;
connections = new Vector();
// Connect to Database
try {
connect(driver,url,user,password);
catch(Exception e) {
e.printStackTrace();
// Simple Database Select
try {
testSimpleSelect();
catch(Exception e) {
e.printStackTrace();
// Database Select
try {
testSelect();
catch(Exception e) {
e.printStackTrace();
* Overloaded constructor for unit tests.
protected AccountServiceImpl() {
poa = null;
* createAccount is used by administrator to add a new Account
* in the system.
* @param newAccount AccountEntryStruct containing data for new account
* @return int the new unique Account ID
* @exception com.kafein.idl.exceptions.DataValidationException
public int createAccount(AccountEntryStruct newAccount) throws
DataValidationException {
validateData (newAccount); // throws DataValidationException;
int accountID = getNextID();
// Create new Account.
Account anAccount = new Account(accountID,
newAccount.userName,
newAccount.userEmail,
newAccount.creditCardType,
newAccount.creditCardNumber,
newAccount.creditCardExpirationDate.year,
newAccount.creditCardExpirationDate.month,
newAccount.userPassword,
newAccount.initialBalance);
// Insert here / call method insertAccount() pass it in an account object
// or call manager object - accountmanager.put()
// Insert Account into Database
try {
insertAccount(anAccount);
catch(Exception e) {
e.printStackTrace();
accounts.put(accountID,anAccount);
return accountID;
* isAccountValid is used to validate a user logon.
* @param accountID AccountID
* @param userPassword String
* @return boolean true to indicate an existing Account
public boolean isValidAccount (int accountID, String userPassword) {
// Get account with key equal to accountID.
AccountStruct anAccount;
try {
anAccount = (AccountStruct) getAccount (accountID);
catch (NotFoundException e) {
return false;
// Verify password.
return (anAccount.userPassword.equals(userPassword) ? true : false);
* getAccount is used to retrieve an existing Account in the system
* @param int AccountID
* @return AccountStruct containing data for the existing Account
* @exception com.kafein.idl.exceptions.NotFoundException
public AccountStruct getAccount(int accountID)throws
NotFoundException {
// Verify that accountID is within an appropriate interval.
if (accountID < 1 || accountID > accounts.size()) {
throw new NotFoundException(DataValidationErrorCodes.INVALID_ACCOUNT_ID,
"Account ID not found");
// Get Account and convert to AccountStruct (which is returned).
Account anAccount = (Account) accounts.get(accountID);
return anAccount.getAccountStruct();
* getAllAccounts is used to retrieve all existing Accounts in the system
* @return AccountStruct[] containing all existing Accounts.
* @fyi returns an empty sequence if no Accounts exist
// GetAllAcounts method v. 2 - rather than enumerating through the vector
// call a method that returns a collection of objs in that method where
// you do select stmts
public AccountStruct[] getAllAccounts() {
// Allocate the array of AccountStructs.
Vector results = new Vector();
try {
results = selectAccounts();
catch(Exception e) {
e.printStackTrace();
//Vector results = selectAccounts();
int lastKey = results.size();
//int lastKey = accounts.size();
AccountStruct[] accountSequence = new AccountStruct[lastKey];
if (lastKey==0) {
return accountSequence;
// Create AccountStructs from Accounts.
for (int i = 1; i <= lastKey; i++) {
Account anAccount = (Account) accounts.get(i);
accountSequence[i-1] = anAccount.getAccountStruct();
return accountSequence;
* validateData is used to check new account data.
* @param newAccount AccountEntryStruct containing data for new account
* @exception com.kafein.idl.exceptions.DataValidationException
protected void validateData(AccountEntryStruct newAccount) throws
DataValidationException {
// Check all of the member data in newAccount.
if (newAccount.userName.equals("")) {
throw new DataValidationException(
DataValidationErrorCodes.INVALID_USER_NAME,
"User Name must not be empty");
if (newAccount.userEmail.equals("")) {
throw new DataValidationException(
DataValidationErrorCodes.INVALID_USER_EMAIL,
"User Email must not be empty");
if (newAccount.creditCardType.equals("")) {
throw new DataValidationException(
DataValidationErrorCodes.INVALID_CREDIT_CARD_TYPE,
"Credit card type must not be empty");
if (newAccount.creditCardNumber.equals("")) {
throw new DataValidationException(
DataValidationErrorCodes.INVALID_CREDIT_CARD_NUMBER,
"Credit card number must not be empty");
// Compare creditCardExpirationDate to current date
// (we only consider year and month).
GregorianCalendar now = new GregorianCalendar();
DateTimeStruct proposed = newAccount.creditCardExpirationDate;
if (proposed.year < now.get (Calendar.YEAR) ||
(proposed.year == now.get (Calendar.YEAR) &&
proposed.month < now.get (Calendar.MONTH) + 1)) {
throw new DataValidationException(
DataValidationErrorCodes.INVALID_CREDIT_CARD_EXPIRATION_DATE,
"Credit card has expired");
if (newAccount.userPassword.equals("")) {
throw new DataValidationException(
DataValidationErrorCodes.INVALID_USER_PASSWORD,
"Password must not be empty");
else if (!newAccount.userPassword.equals(newAccount.userPasswordVerification)) {
throw new DataValidationException(
DataValidationErrorCodes.INVALID_USER_PASSWORD,
"Password verification failure");
if (newAccount.initialBalance < 0.0F) {
throw new DataValidationException(
DataValidationErrorCodes.INVALID_BALANCE,
"Account Balance cannot have a negative balance");
* getNextID is used to generate a unique ID.
* Needs a much better implementation that generates a globally unique ID!
* @return int an Account ID
protected synchronized int getNextID() {
nextAccountID++;
return nextAccountID - 1;
* override _default_POA to return this servant's POA, not Root POA
public POA _default_POA() {
return poa;
* jdbc related methods
public void connect(String driver, String url, String user, String password)
throws Exception {
try {
// Load JDBC driver
Class.forName(driver);
System.out.println("Connecting to " + url);
connection = DriverManager.getConnection(url, user, password);
connections.add(connection);
connection.setAutoCommit(false);
} catch(Exception e) {
System.err.println("System Exception in connect");
System.err.println(e);
throw e;
public void closeConnection() throws Exception {
try {
Enumeration myEnum = connections.elements();
while ( myEnum.hasMoreElements() ) {
System.out.println("Closing connection");
((Connection) myEnum.nextElement()).close();
} catch (Exception e) {
System.err.println("System Exception in closeConnection");
System.err.println(e);
throw e;
private void testSimpleSelect() throws Exception {
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("Select 1 from ACCOUNT");
if (rs != null && rs.next()) {
int value = rs.getInt(1);
System.out.println("Fetched value " + value);
connection.commit();
statement.close();
} catch(Exception e) {
System.err.println("System Exception in testSimpleSelect");
System.err.println(e);
throw e;
private void testSelect() throws Exception {
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(
"Select ACCT_ID, ACCT_USERNAME, ACCT_USEREMAIL, ACCT_CC_TYPE, ACCT_CC_NUMBER, ACCT_CC_EXPYR, ACCT_CC_EXPMO, ACCT_USERPASSWORD, ACCT_USERBALANCE from ACCOUNT LIMIT 1");
System.out.println("Account ID User Name User Email CC Type CC Number CC Expyr CC Expmo User Password User Balance");
while (rs != null && rs.next()) {
int acct_id = rs.getInt(1);
String acct_username = rs.getString(2);
String acct_useremail = rs.getString(3);
String acct_cc_type = rs.getString(4);
String acct_cc_number = rs.getString(5);
int acct_cc_expyr = rs.getInt(6);
int acct_cc_expmo = rs.getInt(7);
String acct_userpassword = rs.getString(8);
float acct_userbalance = rs.getFloat(9);
System.out.println(acct_id + " " +
acct_username + " " +
acct_useremail + " " +
acct_cc_type + " " +
acct_cc_number + " " +
acct_cc_expyr + " " +
acct_cc_expmo + " " +
acct_userpassword + " " +
acct_userbalance);
connection.commit();
statement.close();
} catch(Exception e) {
System.err.println("System Exception in testSelect");
System.err.println(e);
throw e;
private void testLoadData() throws Exception {
int numberOfAccounts = 5;
String acct_username = "<--20 BYTE STRING-->";
String acct_useremail = "<--20 BYTE STRING-->";
String acct_cc_type = "TEST ";
String acct_cc_number = "<--20 BYTE STRING-->";
int acct_cc_expyr = 2000;
int acct_cc_expmo = 1;
String acct_userpassword = "<--20 BYTE STRING-->";
float acct_userbalance = 0.0F;
int acct_id = 0;
try {
System.out.println("Inserting data...");
connection.setAutoCommit(false);
// Calculate Start time
System.out.println("Starting data insertion (" + numberOfAccounts +
" rows) into ACCOUNT table..");
long startTime = System.currentTimeMillis();
preparedStatement = connection.prepareStatement(
"INSERT INTO ACCOUNT (ACCT_ID, ACCT_USERNAME, ACCT_USEREMAIL, ACCT_CC_TYPE, ACCT_CC_NUMBER, " +
"ACCT_CC_EXPYR, ACCT_CC_EXPMO, ACCT_USERPASSWORD, ACCT_USERBALANCE) VALUES ( ?, ?, ?, ?, ?, ? , ?, ?, ?)");
// Insert accounts in ACCOUNT table
for (int i = 1; i <= numberOfAccounts; i++) {
acct_id = i * 1000;
preparedStatement.setInt(1, acct_id);
preparedStatement.setString(2, acct_username);
preparedStatement.setString(3, acct_useremail);
preparedStatement.setString(4, acct_cc_type);
preparedStatement.setString(5, acct_cc_number);
preparedStatement.setInt(6, acct_cc_expyr);
preparedStatement.setInt(7, acct_cc_expmo);
preparedStatement.setString(8, acct_userpassword);
preparedStatement.setFloat(9, acct_userbalance);
preparedStatement.executeUpdate();
connection.commit();
System.out.println(numberOfAccounts + " accounts created.");
preparedStatement.close();
long stopTime = System.currentTimeMillis();
System.out.println("Account table load complete.");
System.out.println("Load time = " +
((stopTime - startTime)/(1000f)) + " seconds");
System.out.println("Data insertion complete");
} catch(Exception e) {
System.err.println("System Exception in loadData");
System.err.println(e);
throw e;
* insertAccount is used to insert a new Account in the Database
* @param int AccountID
* @return AccountStruct containing data for the existing Account
private void insertAccount(Account anAccount) throws Exception {
AccountStruct anAccountStruct = anAccount.getAccountStruct();
int numberOfAccounts = 1;
String acct_username = anAccountStruct.userName;
String acct_useremail = anAccountStruct.userEmail;
String acct_cc_type = anAccountStruct.creditCardType;
String acct_cc_number = anAccountStruct.creditCardNumber;
int acct_cc_expyr = anAccountStruct.creditCardExpirationDate.year;
int acct_cc_expmo = anAccountStruct.creditCardExpirationDate.month;
String acct_userpassword = anAccountStruct.userPassword;
float acct_userbalance = anAccountStruct.accountBalance;
int acct_id = anAccountStruct.accountID;
try {
System.out.println("Inserting data...");
connection.setAutoCommit(false);
//instead of system.out just log
// Calculate Start time
System.out.println("Starting data insertion ( 1" +
" row) into ACCOUNT table..");
long startTime = System.currentTimeMillis();
preparedStatement = connection.prepareStatement(
"INSERT INTO ACCOUNT (ACCT_ID, ACCT_USERNAME, ACCT_USEREMAIL, ACCT_CC_TYPE, ACCT_CC_NUMBER, " +
"ACCT_CC_EXPYR, ACCT_CC_EXPMO, ACCT_USERPASSWORD, ACCT_USERBALANCE) VALUES ( ?, ?, ?, ?, ?, ? , ?, ?, ?)");
acct_id = 1000;
preparedStatement.setInt(1, acct_id);
preparedStatement.setString(2, acct_username);
preparedStatement.setString(3, acct_useremail);
preparedStatement.setString(4, acct_cc_type);
preparedStatement.setString(5, acct_cc_number);
preparedStatement.setInt(6, acct_cc_expyr);
preparedStatement.setInt(7, acct_cc_expmo);
preparedStatement.setString(8, acct_userpassword);
preparedStatement.setFloat(9, acct_userbalance);
preparedStatement.executeUpdate();
connection.commit();
System.out.println("1 account created.");
preparedStatement.close();
long stopTime = System.currentTimeMillis();
System.out.println("Account table load complete.");
System.out.println("Load time = " +
((stopTime - startTime)/(1000f)) + " seconds");
System.out.println("Data insertion complete");
} catch(Exception e) {
System.err.println("System Exception in loadData");
System.err.println(e);
throw e;
private Vector selectAccounts() throws Exception {
try {
// Create Vector to hold individual Account values
Vector mainvector = new Vector();
Vector values = new Vector();
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(
"Select ACCT_ID, ACCT_USERNAME, ACCT_USEREMAIL, ACCT_CC_TYPE, ACCT_CC_NUMBER, ACCT_CC_EXPYR, ACCT_CC_EXPMO, ACCT_USERPASSWORD, ACCT_USERBALANCE from ACCOUNT");
System.out.println("Account ID User Name User Email CC Type CC Number CC Expyr CC Expmo User Password User Balance");
// Iterate through result set
while (rs != null && rs.next()) {
// Make sure values is empty
values.clear();
int acct_id = rs.getInt(1);
String acct_username = rs.getString(2);
String acct_useremail = rs.getString(3);
String acct_cc_type = rs.getString(4);
String acct_cc_number = rs.getString(5);
int acct_cc_expyr = rs.getInt(6);
int acct_cc_expmo = rs.getInt(7);
String acct_userpassword = rs.getString(8);
float acct_userbalance = rs.getFloat(9);
// Populate Vector values
values.addElement(rs.getObject(1));
values.addElement(rs.getObject(2));
values.addElement(rs.getObject(3));
values.addElement(rs.getObject(4));
values.addElement(rs.getObject(5));
values.addElement(rs.getObject(6));
values.addElement(rs.getObject(7));
values.addElement(rs.getObject(8));
values.addElement(rs.getObject(9));
mainvector.addElement(values);
System.out.println(acct_id + " " +
acct_username + " " +
acct_useremail + " " +
acct_cc_type + " " +
acct_cc_number + " " +
acct_cc_expyr + " " +
acct_cc_expmo + " " +
acct_userpassword + " " +
acct_userbalance);
connection.commit();
statement.close();
return mainvector;
} catch(Exception e) {
System.err.println("System Exception in selectAccounts");
System.err.println(e);
throw e;
}line 217 and 218 is
Account anAccount = (Account) accounts.get(i);
accountSequence[i-1] = anAccount.getAccountStruct();
i realized that
Account anAccount = (Account) accounts.get(i);
was a typo. what it should have been was
Account anAccount = (Account) results.get(i);
so my getAllAccounts() method now looks like
* getAllAccounts is used to retrieve all existing Accounts in the system
* @return AccountStruct[] containing all existing Accounts.
* @fyi returns an empty sequence if no Accounts exist
// GetAllAcounts method v. 2 - rather than enumerating through the vector
// call a method that returns a collection of objs in that method where
// you do select stmts
public AccountStruct[] getAllAccounts() {
// Allocate the array of AccountStructs.
Vector results = new Vector();
try {
results = selectAccounts();
catch(Exception e) {
e.printStackTrace();
//Vector results = selectAccounts();
int lastKey = results.size();
//int lastKey = accounts.size();
AccountStruct[] accountSequence = new AccountStruct[lastKey];
if (lastKey==0) {
return accountSequence;
// Create AccountStructs from Accounts.
for (int i = 1; i <= lastKey; i++) {
Account anAccount = (Account) results.get(i);
accountSequence[i-1] = anAccount.however, i still get the same runtime errors.
is my selectAccounts() method returning a null? -
Getting Connected for the First Time with JDBC
Hello everyone. I am trying to make my first database connection to a mysql database with Java. I am using jdk 1.5.0, MySQL 4.1.11 nt, and I think I have the freshly downloaded driver C:\jdk1.5.0\jre\lib\ext\mysql-connector-java-3.0.16-ga-bin.jar" installed in the right spot. When I try to run the following code...
package dbfinder;
import java.sql.*;
import javax.sql.*;
import com.sun.rowset.JdbcRowSetImpl;
import javax.sql.rowset.JdbcRowSet;
import java.sql.ResultSetMetaData;
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
public class DatabaseConnector {
public DatabaseConnector() {
public static void main(String args[]){
Connection connection;
Statement statement;
// ResultSet resultSet;
// ResultSetMetaData metaData;
String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
String DATABASE_URL = "jdbc:mysql://localhost/state_crime";
String USER = "cis695d";
String PASSWORD = "cis695d";
JdbcRowSet rowSet = new JdbcRowSetImpl();
try {
Class.forName(DATABASE_DRIVER); // load database driver
System.out.println("class loaded");
rowSet.setUrl("DATABASE_URL");
rowSet.setUsername(USER);
rowSet.setPassword(PASSWORD);
rowSet.setCommand("Select * FROM state_crime_rates");
rowSet.execute();
ResultSetMetaData metaData = rowSet.getMetaData();
int numberOfColumns;
numberOfColumns = metaData.getColumnCount();
System.out.println(numberOfColumns);
} catch(SQLException sqlException){
sqlException.printStackTrace();
System.exit(1);
catch(ClassNotFoundException classNotFound){
classNotFound.printStackTrace();
System.exit(1);
I get the following exception...
java.sql.SQLException: No suitable driver
at java.sql.DriverManager.getConnection(DriverManager.java:545)
at java.sql.DriverManager.getConnection(DriverManager.java:171)
at com.sun.rowset.JdbcRowSetImpl.connect(JdbcRowSetImpl.java:618)
at com.sun.rowset.JdbcRowSetImpl.prepare(JdbcRowSetImpl.java:630)
at com.sun.rowset.JdbcRowSetImpl.execute(JdbcRowSetImpl.java:526)
at dbfinder.DatabaseConnector.main(DatabaseConnector.java:44)
Does anyone have any ideas? Is it my code? Is there a different driver I should use? Any help would be greatly appreciated.Hello everyone. I am trying to make my first
database connection to a mysql database with Java. I
am using jdk 1.5.0, MySQL 4.1.11 nt, and I think I
have the freshly downloaded driver
C:\jdk1.5.0\jre\lib\ext\mysql-connector-java-3.0.16-ga
-bin.jar" installed in the right spot. You shouldn't be putting that JAR in jre/lib/ext, even if you've found some docs to tell you to do it. Only language extensions (e.g., packages that begin w/javax) belong there.
I get the following exception...
java.sql.SQLException: No suitable driver
Does anyone have any ideas? Is it my code? Is there
a different driver I should use? Any help would be
greatly appreciated.The driver is correct. The class loader found it, even though I think you should use the -classpath option to find the JAR.
It's your code.
What are you doing with all that RowSet stuff?
This works. Study it:
import java.sql.*;
import java.util.*;
* Command line app that allows a user to connect with a database and
* execute any valid SQL against it
public class DataConnection
public static final String DEFAULT_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
public static final String DEFAULT_URL = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\\Edu\\Java\\Forum\\DataConnection.mdb";
public static final String DEFAULT_USERNAME = "admin";
public static final String DEFAULT_PASSWORD = "";
public static final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
public static final String DEFAULT_URL = "jdbc:mysql://localhost:3306/hibernate";
public static final String DEFAULT_USERNAME = "admin";
public static final String DEFAULT_PASSWORD = "";
/** Database connection */
private Connection connection;
* Driver for the DataConnection
* @param command line arguments
* <ol start='0'>
* <li>SQL query string</li>
* <li>JDBC driver class</li>
* <li>database URL</li>
* <li>username</li>
* <li>password</li>
* </ol>
public static void main(String [] args)
DataConnection db = null;
try
if (args.length > 0)
String sql = args[0];
String driver = ((args.length > 1) ? args[1] : DEFAULT_DRIVER);
String url = ((args.length > 2) ? args[2] : DEFAULT_URL);
String username = ((args.length > 3) ? args[3] : DEFAULT_USERNAME);
String password = ((args.length > 4) ? args[4] : DEFAULT_PASSWORD);
System.out.println("sql : " + sql);
System.out.println("driver : " + driver);
System.out.println("url : " + url);
System.out.println("username: " + username);
System.out.println("password: " + password);
db = new DataConnection(driver, url, username, password);
System.out.println("Connection established");
Object result = db.executeSQL(sql);
System.out.println(result);
else
System.out.println("Usage: db.DataConnection <sql> <driver> <url> <username> <password>");
catch (SQLException e)
System.err.println("SQL error: " + e.getErrorCode());
System.err.println("SQL state: " + e.getSQLState());
e.printStackTrace(System.err);
catch (Exception e)
e.printStackTrace(System.err);
finally
if (db != null)
db.close();
db = null;
* Create a DataConnection
* @throws SQLException if the database connection fails
* @throws ClassNotFoundException if the driver class can't be loaded
public DataConnection() throws SQLException,ClassNotFoundException
this(DEFAULT_DRIVER, DEFAULT_URL, DEFAULT_USERNAME, DEFAULT_PASSWORD);
* Create a DataConnection
* @throws SQLException if the database connection fails
* @throws ClassNotFoundException if the driver class can't be loaded
public DataConnection(final String driver,
final String url,
final String username,
final String password)
throws SQLException,ClassNotFoundException
Class.forName(driver);
this.connection = DriverManager.getConnection(url, username, password);
* Get Driver properties
* @param database URL
* @return list of driver properties
* @throws SQLException if the query fails
public List getDriverProperties(final String url)
throws SQLException
List driverProperties = new ArrayList();
Driver driver = DriverManager.getDriver(url);
if (driver != null)
DriverPropertyInfo[] info = driver.getPropertyInfo(url, null);
if (info != null)
driverProperties = Arrays.asList(info);
return driverProperties;
* Clean up the connection
public void close()
close(this.connection);
* Execute ANY SQL statement
* @param SQL statement to execute
* @returns list of row values if a ResultSet is returned,
* OR an altered row count object if not
* @throws SQLException if the query fails
public Object executeSQL(final String sql) throws SQLException
Object returnValue;
Statement statement = null;
ResultSet rs = null;
try
statement = this.connection.createStatement();
boolean hasResultSet = statement.execute(sql);
if (hasResultSet)
rs = statement.getResultSet();
ResultSetMetaData meta = rs.getMetaData();
int numColumns = meta.getColumnCount();
List rows = new ArrayList();
while (rs.next())
Map thisRow = new LinkedHashMap();
for (int i = 1; i <= numColumns; ++i)
String columnName = meta.getColumnName(i);
Object value = rs.getObject(columnName);
thisRow.put(columnName, value);
rows.add(thisRow);
returnValue = rows;
else
int updateCount = statement.getUpdateCount();
returnValue = new Integer(updateCount);
finally
close(rs);
close(statement);
return returnValue;
* Close a database connection
* @param connection to close
public static final void close(Connection connection)
try
if (connection != null)
connection.close();
connection = null;
catch (SQLException e)
e.printStackTrace();
* Close a statement
* @param statement to close
public static final void close(Statement statement)
try
if (statement != null)
statement.close();
statement = null;
catch (SQLException e)
e.printStackTrace();
* Close a result set
* @param rs to close
public static final void close(ResultSet rs)
try
if (rs != null)
rs.close();
rs = null;
catch (SQLException e)
e.printStackTrace();
* Close a database connection and statement
* @param connection to close
* @param statement to close
public static final void close(Connection connection, Statement statement)
close(statement);
close(connection);
* Close a database connection, statement, and result set
* @param connection to close
* @param statement to close
* @param rs to close
public static final void close(Connection connection,
Statement statement,
ResultSet rs)
close(rs);
close(statement);
close(connection);
}% -
I've recently come across the problem of needing to count the number of rows in a potentially large resultset.
I did quite a bit of digging and found that the only suggested answers appear to be:
1. Do a SELECT COUNT(*) before doing the query.
2. Make the ResultSet scrollable, and use rset.last() and rset.getRow().
I have problems with both approaches:
1a. Two queries are issued rather than one - this could be quite expensive.
1b. The queries I am executing are dynamic - thus some clever logic is required to parse the statement and work out what we should be counting.
1c. The number of hits may change between the counting and the actual query.
2a. Definitely most simple, but the Oracle JDBC driver iterates through all the rows to get to the last one, meaning that the whole ResultSet is loaded in to the client-side cache, and thus killing the middle-tier unnecessarily.
2b. The results have to be scrollable - not a problem for me, but is too expensive for some.
I had settled on number 2 for a while, but performance was just too nasty when the ResultSet had more than a few million rows in it, and thus I've spent the last few days looking around for better alternatives.
select inner_2.*, rownum rowcount from (
select inner_1.*, (rownum*-1) neg_row, rownum pos_row from (
select COL1, COL2, COL3
from TABLE1, TABLE2
where TABLE1.COL1 = TABLE2.COL2
order by event_type
) inner_1
order by neg_row asc
) inner_2
order by pos_row asc
Let me explain. This query is determining the rowcount and returning the required columns all in one statement. All I need to do is look at the first row, and read the ROWCOUNT column (the last column) to know how many rows are in the resultset.
The disadvantage of this method is that an extra two sorts are required, and that there are three extra columns on the result set, which the caller didn't ask for. Hiding the extra three column is easy if you want a really clean solution.
These are definitely prices worth paying for me but I acknowledge that not everyone will find this price worth paying. However, having been immensely frustated with the lack of options for solving this problem, I thought I would share my solution with you all.
And on a less-altruistic note, if anyone can tell me how to optimise it further, has a better solution, or knows why it doesn't actually work like it appears to, I'd be more than interested to hear your comments.
MarcusIf you need a consistent resultset, you could create a global temp table-- each session would then query the temp table and see a consistent resultset over time. This has the disadvantage that the database has to duplicate the resultset for each session, which probably only moves the caching problem.
If your sessions don't go on forever and you have sufficient UNDO space, you can set the transaction isolation level to serializable. That will "freeze" the database to the point in time that the session begins. You need to have suffient UNDO, however, for the database to be able to reconstruct the database to that point in time and you need to be able to handle the situation where a user starts a session, walks away for the weekend, and comes back with an error indicating they need to reissue their query.
If you want to really get sophisticated, you can use Oracle Workspace Manager to "branch" the data for each user. Workspace Manager would allow you to keep a consistent view of data forever without duplicating data for each session.
The explain plan approach is useful as a rough estimate, not as an exact count. It's based on the statistics that the CBO is looking at, which ought to be close, but could easily be off by a factor of 2 or more depending on the complexity of the query. To get an actualt honest-to-goodness count, you need to incur the cost of a count(*). It seems to me, though, that if the data is particularly volitile, with the count constantly changing, it wouldn't be particularly useful to know the exact count at a point in time.
Note that the SQL chunking method I outlined above is much more efficient retrieving the first few pages than the last few. If the resultset is large, my assumption is that people aren't actually going page-by-page through the entire thing-- that would seem incedibly inefficient. If they're likely looking at the first few pages and the last few pages, you'd want to have slightly different queries for the first and last few pages-- the inner query's ORDER BY clause would have to be reversed (i.e. ASC for the first pages, DESC for the last few pages). Then, the middle pages would be the most expensive.
Justin
Distributed Database Consulting, Inc.
www.ddbcinc.com/askDDBC -
Distributed JDBC/JMS transaction commit order
I am using WLS 10.3.0. I have an app with container-managed EJBs which participate in distributed transactions using XA drivers for two resources, (1) a jdbc connection to Oracle database, and (2) WebLogic JMS server. In a typical EJB call, I am writing a record to the database and sending a message to a local queue which is being consumed by a MDB. My question is how can I guarantee that by the time the MDB receives the JMS message, the record will be guaranteed to have been committed in the database. It appears that occasionally the record is not yet there. Is there a way to force the jdbc commit to happen before the JMS message gets consumed? I know there is a commit_point_strength parameter that determines commit order for the database resource, but I don't see such a concept for JMS...
"The Default Time-to-Deliver attribute for XAConnectionFactory for the Weblogic JMS connection queue, is a minimum interval from when the message is SENT, to when it is available to be processed. What is really needed is a delay from COMMIT time -- not from the sent time."
<jay>
Not entirely true. Delay is not from when message is “SENT, Default Time-To-Deliver is delay at within JMS subsystem before it delivers message to consumer. It means that "Send" thread will not block for this delay and "Send" side executes no different whether there is "Time-to-Deliver" configured or not.
</jay>
"For example, imagine a distributed transaction does a JMS send, followed by a query that takes 10 seconds, followed by a commit. If Default Time-to-Deliver is set to 5 seconds, it will be completly ignored, since the 10 seconds from the send to the commit is a larger interval. So at commit it is still very possible that the MDB will receive the message before the database transaction is committed."
<jay>
This is not true also. JMS message will be available for delivery only after distributed transaction commits and more specifically "commit" part of the JMS resource completes - clock for "message delivery delay" will not start until distributed transaction is committed. Considering transaction will not commit until slow running query completes execution above scenario will not cause “Default Time-to-Deliver” workaround to fail.
Slow execution of the XA.commit() request from TM (Weblogic) to database may cause concern , however considering that TM (WebLogic) receive response of the XA.prepare() from all participating resources before XA.commit(), commit should execute with delay not more than few milliseconds and chances are negligible that proposed workaround will fail.
</jay>
"The bottom line, is that this parameter is not an effective way to control the race condition unless the JMS send is always performed as the last action in a distributed transaction.
For this reason we have gone with inserting a small configurable sleep at the start of the onMessage() methods in the MDB. Not a very elegant solution, but the one ne that works reliably."
<jay>
I think "Default Time-to-Deliver" is no less effective or no less reliable solution than placing sleep() in onMessage(), however it is more cleaner solution because it uses application server built in feature instead of updating code in onMessage().
</jay>
-jayesh@yagna -
Relative Paths In DSN-less JDBC URL
Whenever I've seen DSN-less URL strings for M$ Access, they've always used an absolute path to the database file:
String url="jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\\full\\path\\src\\data\\FirstLotParts.mdb";Has anyone tried to give a relative path?
String url="jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=src\\data\\FirstLotParts.mdb";I'd like to be able to check out my application to a clean directory and have Ant run JUnit tests without having to change the absolute path. Is it possible? Thanks - MODJust answered my own question: Yes, it does work with a relative path:
String url="jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=.\\src\\data\\FirstLotParts.mdb";MOD -
What are all the ways to clean the ipad smart cover?
my smart cover is getting quite dirty, i would like to know what are the ways of cleaning it without damaging it, itis not a leather cover
XML file may be generated from database table with
1. XML SQL Utility.
2. JDBC 4.0 API. A JDBC 4.0 driver is not yet available and the 'XML' data type is implemented by only SQL Server and IBM DB2.
3. Hibernate 3.1
http://www.hibernate.org/hib_docs/v3/reference/en/html/xml.html
Hibernate 3.1 is the recommended. -
Weblogic 8.1 SP 3 JDBC Connections
Hi,
We have configured JDBC connection pool size with initial 1, increment 1 and max is 15. We are experiencing slow performance with app sometimes. Some select and update operations taking more than 60 secs which usually takes about 15 secs.
I monitered the app during slowness and there were 3 users using the app that time. And application lost the connection with exchange server. The number of active connections in weblogic console were 4 and 5 sometimes. But when I checked with SQL Server DBA he saw 8 connections coming from application. Is there any possibility that the connections established before were not cleaned causing for this slowness.
When we bounce weblogic server it starts working fine as normal.
Does anyone experienced similar problem? I appreciate if anyone can help me in this.
Thanks,
MaheshEven if it is a very naive question but I just cannot get it worked, what do you mean by using jdk 1.5 on client side?
I guess client side is completely out of WLS so the jdk to be used on the client side is not set in the environment.
However, the Exception Im getting is on the server side, when it tries to run the code automatically generated from Kapow Mashup Server 6.3. That code is embedded in a jar file, but it seems it makes a call to the java.lang.StringBuilder class which as said before, it is only available from jdk 1.5 onwards.
Should I contact Kapow Mashup Server support to see how the sample code is generated or I am missing something?
Regards. -
JDBC gives error if accessing Package Synonym
Calling a stored procedure in a package using JDBC...
Where we are using a synonym for our package (given all permissions are OK - I've even tried SYSDBA) rather than calling procedures directly in the package, we get the error 'table or view does not exist'.
This error only occurs for procedures in the package which return ref cursor type (i.e. a recordset), otherwise the procedure seems to execute fine.
The same procedures can happily be used via ODBC and OLEDB using the synonym, so I suspect it is JDBC at fault.
We do need to use a synonym (I like to keep nice clean tidy schemas!) so if anyone knows how to get around it or whether the bug will be fixed shortly please let us know.
Regards
Jason.
nullHi,
Returning refcursors from Java stored proc feature is planned for JDBC 8.2.
Hope this helps,
-Kishore -
Hi,
Everything is set up and running on Redhat7.1. Version 1.3.1 of jdk is
installed and tomcat version 3.2.1.
I also installed the mod_jserv module and started serving jsp pages
which worked perfectly.
I then downloaded the mysql jdbc drivers from the mysql site and
installed them and set the classpath to
correct path in /etc/profile. I get the following error when connecting
to the mysql database:
Root cause:
java.sql.SQLException: Server configuration denies access to data source
at org.gjt.mm.mysql.MysqlIO.init(MysqlIO.java:144)
at org.gjt.mm.mysql.Connection.(Connection.java:230)
at org.gjt.mm.mysql.Driver.connect(Driver.java:126)
at java.sql.DriverManager.getConnection(DriverManager.java:517)
at java.sql.DriverManager.getConnection(DriverManager.java:199)
at
jsp.num._0002fjsp_0002fnum_0002fnumguess_0002ejspnumguess_jsp_59._jspService(_0002fjsp_0002fnum_0002fnumguess_0002ejspnumguess_jsp_59.java:86)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java)
at javax.servlet.http.HttpServlet.service(HttpServlet.java)
at
org.apache.jasper.servlet.JspServlet$JspServletWrapper.service(JspServlet.java)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java)
at javax.servlet.http.HttpServlet.service(HttpServlet.java)
at org.apache.tomcat.core.ServletWrapper.doService(ServletWrapper.java)
at org.apache.tomcat.core.Handler.service(Handler.java)
at org.apache.tomcat.core.ServletWrapper.service(ServletWrapper.java)
at
org.apache.tomcat.core.ContextManager.internalService(ContextManager.java)
at org.apache.tomcat.core.ContextManager.service(ContextManager.java)
at
org.apache.tomcat.service.http.HttpConnectionHandler.processConnection(HttpConnectionHandler.java)
at org.apache.tomcat.service.TcpWorkerThread.runIt(PoolTcpEndpoint.java)
at
org.apache.tomcat.util.ThreadPool$ControlRunnable.run(ThreadPool.java)
at java.lang.Thread.run(Thread.java:484)
Heres the code that i used.
<html><body>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.servlet.*"%>
<%@ page import="javax.servlet.http.*"%>
<%
//try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
Connection Conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?user=root&password=");
Statement Stmt = Conn.createStatement();
String SQL="SELECT * from user";
ResultSet RS = Stmt.executeQuery(SQL);
while (RS.next()) {
System.out.println(RS.getString(1));
// Clean up after ourselves
RS.close();
Stmt.close();
Conn.close();
//catch (SQLException E) {
// System.out.println("SQLException: " + E.getMessage());
// System.out.println("SQLState: " + E.getSQLState());
// System.out.println("VendorError: " + E.getErrorCode());
%></body></html>
Now if I uncomment the commented code I get no error but I also get no
results which is wrong.
I'm thinking there is a priviledge problem. The mysql database is set up
to alloow any user to connect.
Any help would be greatly appreciated.
WinstonI had this problem a few days ago myself and finally went to the developer of the mySQL driver. According to the developer, RedHat, for some unknown reason, maps
127.0.0.1 to "localhost.localdomain". To fix the problem, I had to change the host in my db table from "localhost" to "localhost.localdomain". In my URL, I still used 'localhost'. I also did this in my user table.
Example:
Update user set host = "localhost.localdomain"
where host = "localhost";
Update db set host = "localhost.localdomain"
where host = "localhost";
This works for me through JDBC on Redhat.
Maybe you can help me. Where did you put your driver class files? I tried putting them in WEB-INF/lib and that didn't seem to work. I tried putting them in WEB-INF/classes and that didn't seem to work either. I keep getting, "no suitable driver" which means it has something to do with the CLASSPATH. Unfortunately, since I am using a hosting company that is unfamiliar with servlets, I am limited on what I can get them to do. -
Java.lang.OutOfMemoryError (Microsoft SQL Server JDBC driver)
Hi everyone,
I am getting a java.lang.OutOfMemoryError when performing a simple query to a database. The query produces only one row (and will always produce only one row). However, the statement that produces the second column in the resultset is very long (>256) characters, so could that be it?
Also, I am executing thousands of SQL statements with no difficulty. I have double-checked that I am cleaning up all of my database resources, so I don't think that this is it. Do I have to do anything else besides closing the statement and resultset?
There is no stack trace, otherwise I would have posted it :(
Also, as an aside - is the Microsoft JDBC driver for SQL Server the best one to use? It seems poorly supported and slow at times. Are there any alternatives?
Thanks for your time :)
BenIt is running after thousands of other queries. I'll test to see what happens if I run it by itself.
I am closing the connection. In fact, I am running all of these statements over the same connection and simply opening and closing resultsets.
So a bug in the driver you think?
Thanks for the reply :)
Ben -
Choosing jdbc driver for Oracle 9.0.1 with sdk 1.4.1?
Hi all experts...
I am really beating my head over this... I had java sdk 1.3.1 installed and i am writing an application for oracle database 9.0.1 The driver i had was a classes12.zip file that i included in the classpath to run the application.
Now, i have upgraded my java to 1.4.1 but my application is not picking up the zip file anymore! I am getting No suitable driver:08001 error and NoClassDefFoundError. I checked the oracle website, they dont have a 9.0.1 driver for sdk 1.4.
Is my current driver compatible?
Do i have to upgrade my oracle DB to 9.2 and use another driver?
Or is just one of those classpath problems?
Part of my code is given below:
private static Statement createStatement(String driver, String url, String user, String password)throws IllegalArgumentException, SQLException, ClassNotFoundException
if (url == null || driver == null)
throw new IllegalArgumentException("No database specified");
try
Class.forName(driver);
catch(ClassNotFoundException e)
System.out.println("Class not found: "+driver);
conn = DriverManager.getConnection(url, user, password);
return conn.createStatement();
CLASSPATH=C:\projects\MauiWSxml\resources\classes12.zip;
I will be grateful to any help ...Pleeeeessseeee
Thanks in advanceGreat progress! Excellent!
I'd recommend that you get rid of that CLASSPATH system variable immediately. Don't use it anymore.
I don't know what code you're using, but I KNOW that what I'm posting next will work:
import java.sql.*;
import java.util.*;
public class DataConnection
public static final String DEFAULT_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
public static final String DEFAULT_URL = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\\Edu\\Java\\Forum\\DataConnection.mdb";
public static final String DEFAULT_USERNAME = "admin";
public static final String DEFAULT_PASSWORD = "";
/** Database connection */
private Connection connection;
* Driver for the DataConnection
* @param command line arguments
* <ol start='0'>
* <li>SQL query string</li>
* <li>JDBC driver class</li>
* <li>database URL</li>
* <li>username</li>
* <li>password</li>
* </ol>
public static void main(String [] args)
DataConnection db = null;
try
if (args.length > 0)
String sql = args[0];
String driver = ((args.length > 1) ? args[1] : DEFAULT_DRIVER);
String url = ((args.length > 2) ? args[2] : DEFAULT_URL);
String username = ((args.length > 3) ? args[3] : DEFAULT_USERNAME);
String password = ((args.length > 4) ? args[4] : DEFAULT_PASSWORD);
db = new DataConnection(driver, url, username, password);
Object result = db.executeSQL(sql);
System.out.println(result);
else
System.out.println("Usage: db.DataConnection <sql> <driver> <url> <username> <password>");
catch (SQLException e)
System.err.println("SQL error: " + e.getErrorCode());
System.err.println("SQL state: " + e.getSQLState());
e.printStackTrace(System.err);
catch (Exception e)
e.printStackTrace(System.err);
finally
if (db != null)
db.close();
db = null;
* Create a DataConnection
* @throws SQLException if the database connection fails
* @throws ClassNotFoundException if the driver class can't be loaded
public DataConnection() throws SQLException,ClassNotFoundException
this(DEFAULT_DRIVER, DEFAULT_URL, DEFAULT_USERNAME, DEFAULT_PASSWORD);
* Create a DataConnection
* @throws SQLException if the database connection fails
* @throws ClassNotFoundException if the driver class can't be loaded
public DataConnection(final String driver,
final String url,
final String username,
final String password)
throws SQLException,ClassNotFoundException
Class.forName(driver);
this.connection = DriverManager.getConnection(url, username, password);
* Clean up the connection
public void close()
try
this.connection.close();
catch (Exception e)
; // do nothing; you've done your best
* Execute ANY SQL statement
* @param SQL statement to execute
* @returns list of row values if a ResultSet is returned,
* OR an altered row count object if not
* @throws SQLException if the query fails
public Object executeSQL(final String sql) throws SQLException
Object returnValue = null;
Statement statement = this.connection.createStatement();
boolean hasResultSet = statement.execute(sql);
if (hasResultSet)
ResultSet rs = statement.getResultSet();
ResultSetMetaData meta = rs.getMetaData();
int numColumns = meta.getColumnCount();
List rows = new ArrayList();
while (rs.next())
Map thisRow = new LinkedHashMap();
for (int i = 1; i <= numColumns; ++i)
String columnName = meta.getColumnName(i);
Object value = rs.getObject(columnName);
thisRow.put(columnName, value);
rows.add(thisRow);
rs.close();
statement.close();
returnValue = rows;
else
int updateCount = statement.getUpdateCount();
returnValue = new Integer(updateCount);
return returnValue;
}Put this code in a directory with your classes12.zip. Type:
javac -d . -classpath classes12.zip DataConnection.javaYou should get a DataConnection.class file in that directory. Then type:
java -classpath classes12.zip DataConnection <sql> oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@<host>:1521:<database> <username> <password>where <sql> is any SQL statement that will work against your Oracle instance, <host> is the database server, <database> is the Oracle instance, <username> and <password> give you access to Oracle. (DON'T type the chevons <> - I just included them for illustration.)
If that won't connect, change the name of classes12.zip to classes12.jar and try again.
This WILL work. - MOD -
Hi,
I'm using JDBC-ODBC bridge to access and query my Excel file.
This part of my code:
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
c = java.sql.DriverManager.getConnection( "jdbc:odbc:qa-list", "", "" );
stmnt = c.createStatement();
qa-list is the ODBC bridge i have created on Windows ODBC Panel.
This works good but i would like to create this ODBC bridge from my program.
The goal is to let user choosing an Excel file, create on the fly the ODBC bridge to be able to query
the Excel sheet...
Do you have any ideas of the way to do that ???
Thanks by advance
R�miOne solution (not pretty) is to take the suggestion to update the registry yourself by creating a .reg script file and invoking regedit on it via Runtime.exec(). Ugly, but it should work.
You could also look at Neva Object Technologies Coroutine package and iteract with the registry directly - it works quite well and they have a few (if I recall) registry examples. This would allow you to create, use then cleaup such entries. Consider adding a Runtime.addShutdownHook() to make sure you always clean out your entries).
http://www.nevaobject.com/_docs/_coroutine/coroutine.htm
Hope that helps.
Chuck
Maybe you are looking for
-
Can I add my icloud @me address to my macmail
I added my first iCloud "@me" e-mail address on my iPad. But, I would also like to receive/send e-mail from my @me account from my iMac and MacMail app. Can I do this? (Many thanks sane Apples)
-
I installed a new 1tb WD hardrive in my mid 2009 macbook pro along with upgrading from 4gb to 8 gb. My start up disk is still almost full, booting up is extremely slow, and programs open up by themselves once booted up ex:word, excel. New TB drive sh
-
Install and Configure Oracle client in Fedora core 3
Hi guys I am raghu , I need a help regarding Oracle client installation in Fedora core 3 can any one guide where to get oracle client and installation steps Thanks Raghu
-
Wimax (Clear) issues with the T400/intel 5150
Hey everyone, thanks in advance for any help! My T400 came in a few days ago, and I'm quite happy with it. I ordered and my computer shipped with the 5150 wimax card in it as Clear recently added service for my city. While everything else works perfe
-
Whatever Happened to TechNote fb1634cb?
I'm fairly certain I need this Technote fb1634cb which explains: "A damaged Windows system registry or incorrect permissions in the registry may prevent Flash Player from installing or registering correctly." and "SUPPORT ALERT Do you have problems i