Jdbc database access
The following is not running and it got compiled . I want to know whether it is possible to open a recordset
for processing based on a value from another recordset .
I need to get values from a recordset based on a value from previous recordset.. Nesting of loops is done for that purpose...
Please clarify in this issue..
The code is enclosed:
import java.sql.*;
import java.math.*;
import java.io.*;
import java.awt.*;
public class Test {
public static void main (String args []) throws Exception {
DriverManager.registerDriver (new sun.jdbc.odbc.JdbcOdbcDriver());
Connection conn = DriverManager.getConnection ("jdbc:odbc:eash","sa","sa");
Statement stmt = conn.createStatement ();
stmt.executeUpdate("use pubs");
ResultSet rset = stmt.executeQuery ("SELECT * FROM publishers");
while (rset.next ()){
System.out.println (rset.getString (1));
ResultSet rs = stmt.executeQuery ("SELECT title FROM titles where pub_id = " + rset.getString (1));
while(rs.next())
System.out.println (rs.getString (1));
hi,
the problem i think is in the fact that when u query that resultset twice, it seems to work the first time but not the second. you could do the following changes and give it a try.
System.out.println (rset.getString (1));
ResultSet rs = stmt.executeQuery ("SELECT title FROM titles where pub_id = " + rset.getString (1));to correct the problem, first store the result of rset.getString(1) into a String variable and then use that. for eg
String value = rset.getString(1);
System.out.println (value);
ResultSet rs = stmt.executeQuery ("SELECT title FROM titles where pub_id = " + value);hope that helpz
cheerz
ynkrish
Similar Messages
-
Access to Database Access from JDBC
Hello,
I have a RFC to JDBC scenario.
The database is on a different machine to the XI, but from XI is going to map a drive to see the database.
In the communication channel I specified the drive with the rest of the path:
jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=Z:/TestDB.mdb
and I get an error:
com.sap.aii.af.ra.ms.api.DeliveryException: Database connection could not be established
Is it possible to access an Access database that is not physically in the machine XI?
thanks very much,hi silvia
first, you need to install JDBC driver in PI to be able to connect to MS Access.
please, see these links
https://forums.sdn.sap.com/click.jspa?searchID=24103238&messageID=7100823
Re: MS access o XI : External driverof access is required or not.
Regarding File to JDBC/MS Access database
https://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/f04ce027-934d-2a10-5a8f-fa0b1ed4d88f
thanks
PD:points if useful
Rodrigo -
Accessing values in Value Mapping from JDBC database during runtime.
Hi all,
I have a query here.
Actually we have to populate the value mapping from a JDBC database, I've gone through the blogs but all of them expalin the value mapping replication process where in SAP tables are the source and it includes ABAP programming, where as my source system is a JDBC database.
Please provide me with the detailed steps to be carried out in IR and ID to accomplish this task.
Thanks once again.
YounusHi Younus,
search the blogs with "lookup". I guess you will find you solution.
Regards Mario -
BIB-16613 Database access error occurred while connecting to the OLAP insta
I am trying to connect to the database using the BI Beans sample bootstrap.jpr
I am getting the BIB-16613 error.
oracle.dss.security.BISecurityException: BIB-16613 Database access error occurred while connecting to the OLAP instance.
java.sql.SQLException: Io exception: The Network Adapter could not establish the connection
The bi_checkconfig utility gives me:
C:\utils\JDev903\bibeans\bin>bi_checkconfig -h pavelr -po 1521 -sid LOCAL -u BIBDEMO -p BIBDEMO
BI Beans Diagnostics(v1.0.0.0) 17/03/03
===============================================================================
JDEV_ORACLE_HOME ............................. = C:\utils\JDev903
JAVA_HOME .................................... = C:\OraHome1\jdk
JDeveloper version ........................... = 9.0.3.1035 (Production)
BI Beans version ............................. = 9.0.3.4.0
BI Beans internal version .................... = 2.7.0.11.3
Connect to database .......................... = Successful
JDBC driver version .......................... = 9.2.0.1.0
JDBC JAR file location ....................... = C:\utils\JDev903\jdbc\lib
Database version ............................. = 9.2.0.2.1
OLAP Catalog version ......................... = N/A
OLAP AW Engine version ....................... = N/A
OLAP API Server version ...................... = N/A
BI Beans Catalog version ..................... = N/A; not installed in BIBDEMO
OLAP API JAR file version .................... = 9.2
OLAP API JAR file location ................... = C:\utils\JDev903\jdev\lib\ext
Load OLAP API metadata ....................... = Successful
Number of metadata folders ................... = 3
Number of metadata measures .................. = 26
Number of metadata dimensions ................ = 22
Metadata output location ..................... = C:\utils\JDev903\bibeans\bin\bi_metadata.txt
I can connect to OLAP BIBDEMO (and SH) schema using OEM.
I can connect to BIBDEMO from JDev Connections (Catalog connection to BIBCAT, OLAP connection to BIBDEMO).
How can I establish the connection from the bootstrap sample?
PavelPlease try follow the steps under "Installing and Configuring the Samples "http://otn.oracle.com/products/bib/htdocs/samples/installing_samples.html - the section titled "Update the samples project settings".
-
Hi All,
I am using oracle 11g client library on Linux 64bit machine and trying to connect to oracle database using jdbc thin driver.
The url format what I am trying to use is:
jdbc:oracle:thin:@IP address:port:service_name
When service_name = orcl : I am able to connect with the above syntax.
But when the service_name is having . e.g service_name = orcl.177.39.45, with the above format I get the above error.
If I change the URL syntax to following, it works
jdbc:oracle:thin:@IP address:port/service_name
But both seems to be valid syntax.
So I would like to undestand the reason behind the same.
When service_name is having ".", why ":" does not work and "/" works and when the service_name is without " ." , 1st format works.
Is there any specific reason behind same?
Please let me know,
Thanks,
AaratiHello,
as per the suggetion, I replaced the URL in the format
URL=jdbc:oracle:thin:@15.154.47.235:1521/ORCL
original URL :
URL=jdbc:oracle:thin:@15.154.47.235:1521:ORCL
With this I was able to access the main page and was not getting database access.
But when I tried to perform some operations say list the submitted jobs, our application internally contacts Oracle database and gets the information stored in the database.
its not able to get and it throws exception.
So is there any reason behind this?
Pasting our application logs for your referance
Thu Aug 08 17:03:33 http-0.0.0.0-9000-1: [ERROR] Exception occurred
com.hp.om.hpos.model.OperationException: Error listing jobs
at com.hp.om.hpos.model.DPAUtils.DPAlistJobsInDB(DPAUtils.java:98)
at com.hp.om.hpos.model.DomainGroup.listSubJobsInDB(DomainGroup.java:96)
at com.hp.om.hpos.model.DomainGroup.listSubJobs(DomainGroup.java:91)
at com.hp.om.wc.model.jobmanager.pagingmanager.PagingManager.ListJobs(PagingManager.java:381)
at com.hp.om.wc.webapp.jobmanager.actions.AbstractJobSearchAction.loadSortedJobListing(AbstractJobSearchAction.java:49)
at com.hp.om.wc.webapp.jobmanager.actions.AbstractJobSearchAction.loadJobListing(AbstractJobSearchAction.java:30)
at com.hp.om.wc.webapp.jobmanager.actions.BasicSearchAction.doExecute(BasicSearchAction.java:358)
at com.hp.om.wc.webapp.jobmanager.actions.WCBaseAction.execute(WCBaseAction.java:81)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:419)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
~
~
Thanks,
aarati -
How to use taglibs in JSP for Database access
Hi
Could any one please tell me how to use taglibs in JSP for Database access
with regrds
JojoThis is a sample how to connect to a MySQL database with JSTL 1.0:
<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
<%@ taglib uri="http://java.sun.com/jstl/sql" prefix="sql" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>JSTL MySQL</title>
<link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<c:catch var="e">
<sql:setDataSource var="datasource" url="jdbc:mysql://Your_Server_Name_Here/You_Schema_Here"
user="Your_Username_Here" password="Your_Password_Here"
driver="com.mysql.jdbc.Driver"/>
<c:out value="datasource= ${datasource}, Class = ${driver.class}"/>
<br />
<br />
<sql:query var="deejays" dataSource="${datasource}">SELECT * FROM Your_Table_Name_Here</sql:query>
<table>
<%-- Get the column names for the header of the table --%>
<c:forEach var="columnName" items="${deejays.columnNames}"><th><c:out value="${columnName}"/></th></c:forEach>
<tbody>
<%-- Get the value of each column while iterating over rows --%>
<c:forEach var="row" items="${deejays.rows}">
<tr><c:forEach var="column" items="${row}">
<td><c:out value="${column.value}"/></td>
</c:forEach>
</tr>
</c:forEach>
</tbody>
</table>
</c:catch>
<br />
<br />
<c:if test="${e!=null}"><span class="error">Error</span>�
<c:out value="${e}" />
</c:if>
</body>
</html>And this thread might help you:
http://forum.java.sun.com/thread.jspa?threadID=639471&tstart=44 -
Database access with JSP custom tags
i have created one file in which i am making the connection with mysql data base with con.mysql.jdbc.Driver.and usking J connector and that i'm doing with custom tag.this is the error which i'm getting in tomcat.
and the tag handler class and TLD file and jsp file is below
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: javax.servlet.jsp.JspException: null
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl .java:841)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.j ava:778)
org.apache.jsp.DbTry_jsp._jspService(org.apache.jsp.DbTry_jsp:72)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:99)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:325)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:245)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
root cause
java.lang.NullPointerException
Try.Connect.<init>(Connect.java:26)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
java.lang.reflect.Constructor.newInstance(Unknown Source)
java.lang.Class.newInstance0(Unknown Source)
java.lang.Class.newInstance(Unknown Source)
org.apache.jasper.runtime.TagHandlerPool.get(TagHandlerPool.java:116)
org.apache.jsp.DbTry_jsp._jspx_meth_db_connect_0(org.apache.jsp.DbTry_jsp:84)
org.apache.jsp.DbTry_jsp._jspService(org.apache.jsp.DbTry_jsp:62)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:99)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:325)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:245)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
note The full stack trace of the root cause is available in the Apache Tomcat/5.5.4 logs.
Apache Tomcat/5.5.4
Tag handler class
package Try;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
import java.sql.*;
public class Connect extends TagSupport {
private String driver = "com.mysql.jdbc.Driver";
private String dbtype = "mysql";
private String host = "localhost";
private String username = "root";
private String password = "203131";
private String database = "compose";
private String scope = "page";
private String id = "";
JspWriter out = pageContext.getOut();
public void setDriver(String str) {
driver = str;
public void setDbtype(String str) {
dbtype = str;
public void setHost(String str) {
host = str;
public void setUsername(String str) {
username = str;
public void setPassword(String str) {
password = str;
public void setDatabase(String str) {
database = str;
public void setScope(String str) {
scope = str;
public void setId(String str) {
id = str;
public int doStartTag() throws JspException {
try {
Class.forName("com.mysql.jdbc.Driver");
String url= "jdbc:" + dbtype + "://" + host + "/" + database;
Connection connection = DriverManager.getConnection(url,username,password);
out.println("right ;;one");
catch (SQLException e1) {
System.out.println("Error in HeadingTagv: " + e1);
catch (Exception e) {
System.out.println("Error in HeadingTag: " + e);
return SKIP_BODY;
TLD is lib.tld
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>db</short-name>
<display-name>Database Tags</display-name>
<description>
A set of tags for working with SQL database access
</description>
<tag>
<name>connect</name>
<tag-class>Try.Connect</tag-class>
<body-content>empty</body-content>
<description>
</description>
<attribute>
<name>driver</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
<description>
</description>
</attribute>
<attribute>
<name>dbtype</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
<description>
</description>
</attribute>
<attribute>
<name>host</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
<description>
Can be given by a run-time expression.
Host name of the computer where database is located.
Default is "localhost".
</description>
</attribute>
<attribute>
<name>username</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
<description>
Can be given by a run-time expression.
Username for logging onto the database.
Default is "root".
</description>
</attribute>
<attribute>
<name>password</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
<description>
Can be given by a run-time expression.
Password for logging onto the database.
Default is the empty string.
</description>
</attribute>
<attribute>
<name>database</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
<description>
Can be given by a run-time expression.
The name of the database that will be used for
the SQL commands. Default is no database specified.
</description>
</attribute>
<attribute>
<name>id</name>
<required>false</required>
<description>
</description>
</attribute>
<attribute>
<name>scope</name>
<required>false</required>
<description>
</description>
</attribute>
</tag>
</taglib>
JSP file is
<%@ taglib uri="/WEB-INF/lib.tld" prefix="db" %>
<html>
<body>
<db:connect username="root" password="203131" database="compose" />
</body>
</html>Answered in your other post:
http://forum.java.sun.com/thread.jspa?threadID=608780&tstart=0 -
Hi All,
I am having major difficulties with my web application on Sun Web Server 6.1.
After a few days of moderate use (ca. 60 database accesses an hour), my web
server locks up and gives time out errors when requests are made.
After discussing this with fellow programmers, I thought my problem
stems from the database access I use. I wasn't using database connection
pooling, so I thought that might be the answer.
Using the Web server's JDBC Connection Pooling, I set up pooling to work with my application.
Everything seemed to work fine, but after a few days of use, the web server once again locked
up.
Below, please find the class I use to query databases. Do you have suggestions as to how to stream this class or suggestions as to where errors might lurk? Can you see any potential issues with the code I have written?
This class is accessed in the following way: From another class, this call is made:
ConnectAndQuery caq = new ConnectAndQuery();
Vector result = caq.getSelect("Select * from table", theDatabaseIwanttoAccess);
--> now goes to appropriate method in below ConnectAndQuery class
------------------------- ConnectAndQuery.class ----------------------------------------------------
import java.io.*;
import java.net.*;
import java.util.*;
import java.sql.*;
import javax.sql.*;
import javax.naming.InitialContext;
import com.sun.gscc.backend.PropertiesGrabber;
import com.sun.gscc.backend.Communicator;
* Manages database connections.
* @author me
* @version 1.0, 2003-12-02
public class ConnectAndQuery {
protected String sql = "";
protected String dbName = "";
public Connection conn;
public DataSource source;
public Statement stmt;
PropertiesGrabber pg = new PropertiesGrabber();
Communicator c = new Communicator();
* Setter for the sql variable.
* @param givenSql The sql required to process
public void setSql(java.lang.String givenSql) {
sql = givenSql;
* Sets the dbName needed to commect
* to the correct database.
* @param givenDbName Name of the database - name and connections specified within this class
public void setDbName(java.lang.String givenDbName) {
dbName = givenDbName;
* Check completeness of data.
* If sql or dbName not present it'll return false.
* @return String Checks if data is available
protected String checkDataAvailability(){
String returnValue = "";
if(dbName == ""){
returnValue += "\nNo database selected for query";
if(sql == ""){
returnValue += "\nNo SQL statement for query action";
return returnValue;
* Returns the appropriate connection to the required database.
* @return String connection string
* @exception SQLException
* @exception Exception
protected String getConnection(){
try{
InitialContext initContext = new InitialContext();
// First, if test conditions, switch to appropriate test databases.
if(dbName == "sccweb" && pg.getValue("testConditions") != null && pg.getValue("testConditions").equals("true")){
dbName = "yikes";
if(dbName == "maize" && pg.getValue("testConditions") != null && pg.getValue("testConditions").equals("true")){
dbName = "thefarm";
// Then, get connection from configured pool
source = (DataSource) initContext.lookup("java:comp/env/jdbc/" + dbName);
conn = source.getConnection();
stmt = conn.createStatement();
//System.err.println("Opening: " + conn.toString());
return conn.toString();
}catch (SQLException e){
c.emailThis(pg.getValue("adminEmail"), "SCCWebError", "SCCWeb Error: [ConnectAndQuery.getConnection] SQLException", "dbName tried: " + dbName + "\nSQLException: " + e.toString());
return "ConnectAndQuery, SQL Exception:\n" + e.toString();
}catch (Exception e){
c.emailThis(pg.getValue("adminEmail"), "SCCWebError", "SCCWeb Error: [ConnectAndQuery.getConnection] Exception", "dbName tried: " + dbName + "\nException: " + e.toString());
return "ConnectAndQuery, Some other getConnection Exception:\n" + e.toString();
* Takes care of insert, update and delete requests.
* Must have set both dbName as well as the sql String.
* Will return number of rows affected as String.
* @return String Number of rows affected
* @exception SQLException
* @exception Exception
public String getInsertDelete() {
// If insufficient data, bail out miserably
String complete = checkDataAvailability();
String returnValue = "not set";
if(complete != ""){
return "Complete Error: " + complete;
}else{
int rv = 0;
try{
String success = getConnection(); // get this from another function to get correct db
rv = stmt.executeUpdate(sql);
returnValue = "" + rv;
}catch (Exception e){
c.emailThis(pg.getValue("adminEmail"), "SCCWebError", "SCCWeb Error: [ConnectAndQuery.getInsertDelete] Exception", "getInsertDelete Exception: " + e.toString() + "\nWith: " + sql);
returnValue = "ConnectAndQuery, at getInsertDelete, Some other Exception:\n" + e.toString();
}finally{
try{
stmt.close();
conn.close();
}catch(Exception e){
c.emailThis(pg.getValue("adminEmail"), "SCCWebError", "SCCWeb Error: [ConnectAndQuery.getInsertDelete] Exception", "Close() Exception: " + e.toString());
return returnValue;
* Processes Insert and Delete requests with given SQL and DB Name.
* @param givenSql
* @param givenDbName
* @return String Number of rows affected
public String getInsertDelete(String givenSql, String givenDbName){
sql = givenSql;
dbName = givenDbName;
return getInsertDelete();
* Takes care of Select statements.
* Must have set both dbName as well as the sql String.
* Will return a vector.
* @return Vector of Hashes containing the Results of the query
* @exception SQLException
* @exception Exception
public Vector getSelect(){
// If insufficient data, bail out miserably
String complete = checkDataAvailability();
String returnTest = "not set";
Vector returnValue = new Vector();
String connectionString = "not set";
if(complete != ""){
returnTest = "Complete Error: " + complete;
}else{
try{
connectionString = getConnection();
StringBuffer query = new StringBuffer(sql);
ResultSet result = stmt.executeQuery(query.toString());
ResultSetMetaData rsmd = result.getMetaData();
while(result.next()){
Hashtable hash = new Hashtable();
for(int i = 1; i <= rsmd.getColumnCount(); i++){
//System.err.println("-------------------------------");
//System.err.println("SQL: " + sql);
//System.err.println("Index: " + i);
//System.err.println("Test: " + rsmd.getColumnName(i));
//System.err.println("Result: " + result.getString(i));
if(result.getString(i) != null){
hash.put(rsmd.getColumnName(i),result.getString(i));
}else{
hash.put(rsmd.getColumnName(i),"");
returnValue.addElement(hash);
}catch (Exception e){
c.emailThis(pg.getValue("adminEmail"), "SCCWebError", "SCCWeb Error: [ConnectAndQuery.getSelect] Exception", "getSelect Exception: " + e.toString() + "\nWith: " + sql);
returnTest = "ConnectAndQuery, getSelect, Some other getSelect Exception:\n" + e.toString();
}finally{
try{
stmt.close();
conn.close();
//System.err.println("closing: " + connectionString);
}catch(Exception e){
c.emailThis(pg.getValue("adminEmail"), "SCCWebError", "SCCWeb Error: [ConnectAndQuery.getSelect] Exception", "Close() Exception: " + e.toString());
return returnValue;
* Takes care of Select statements with given SQL.
* Must have set both dbName as well as the sql String.
* Will return a vector.
* @return Vector with Results of the query
* @exception SQLException
* @exception Exception
public Vector getSelect(String givenSql, String givenDbName){
sql = givenSql;
dbName = givenDbName;
return getSelect();
}When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read and prevents accidental markup from array indices like [i].
-
Hi im trying to access my ORACLE database through a jsp program. The page loads up in the browser, no errors or anything like that, but i get no output.
I am running things on localhost with TomCat 3.2.3
Here is the code, any help gratefully appreciated.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Testing Database Access</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6" TEXT="#000000" LINK="#0000EE"
VLINK="#551A8B" ALINK="#FF0000">
<CENTER>
<TABLE BORDER=5 BGCOLOR="#EF8429">
<TR><TH CLASS="TITLE">
Testing Database Access</TABLE>
</CENTER>
<P>
<P>
Here Is what Might be in the Database
<P>
<%@ page language="java" %>
<%@ page import="java.util.*" %>
<%@ page import="oracle.jdbc.driver.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %>
<%
try
%>
<%
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
String username = "Donnchadh", password = "zcbu5mya";
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@kiwi.isg.computing.dcu.ie:1521:kiwi",username,password);
java.sql.Statement stmt = conn.createStatement();
String query = "SELECT * FROM PERSONALS";
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
int ccount = rs.getMetaData().getColumnCount();
for( int i = 1; i <= ccount; i++ )
System.out.print(rs.getString(i)+"\t");
System.out.println();
%>
<%
rs.close();
stmt.close();
if(conn != null)
try
conn.close();
catch(Exception e)
return;
catch(Exception e)
return;
%>
<P>
</BODY>
</HTML>
I have also tried to access columns directly with this code in the while loop
while(rs.next())
String Title = rs.getString("title");
String FName = rs.getString("fname");
String LName = rs.getString("lname");
String Phone = rs.getString("phone1");
String Phone2 = rs.getString("phone2");
String Addr = rs.getString("addr");
String County = rs.getString("county");
String Country = rs.getString("country");
out.println("<tr><td>" + Title + "</td><td>" + FName + "</td><td>" + LName
+ "</td><td>" + Phone + "</td><td>" + Phone2 + "</td></tr>" + "</td></tr>" + Addr
+ "</td></tr>" + County + "</td></tr>" + Country + "</td></tr>" );i give a servlet access to oracle ,that have test ok!
import java.sql.*;
import javax.servlet.*;
import javax.sql.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class TestServlet1 extends HttpServlet {
private static final String CONTENT_TYPE = "image/jpeg; charset=GBK";
//Initialize global variables
String strRno =null;
ResultSet rs=null;
byte [] buf=null;
InputStream in;
int IntNo;
public void init() throws ServletException {
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
// PrintWriter out = response.getWriter();
// System.out.println("TEst database prepaired ok��");
strRno = request.getParameter( "PictNo" );
IntNo = 0;
if( strRno != null ) {
try { IntNo = Integer.parseInt( strRno ); }
catch( NumberFormatException e ) {
strRno = null;
System.out.println("��������������������"); }
else
System.out.println("��������������������");
if( strRno == null ) {
// response.sendError( HttpServletResponse.SC_NOT_FOUND );
return;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
catch (ClassNotFoundException ex2) {
// out.println("TEst2��");
// System.out.println("TEst2�� ex2��");
String url="jdbc:oracle:thin:@erdos00:1521:erdos";
Connection con = null;
try {
con = DriverManager.getConnection(url, "system", "manager");
catch (SQLException ex1) {
//out.println("TEst�� ex1");
System.out.println("TEst�� ex1��");
// PreparedStatement sql=con.PrepareStatement("select photo from blob_test WHERE rno = IntNo" );
PreparedStatement sql = null;
try {
sql = con.prepareStatement("select photo from blob_test WHERE rno = 14 ");
// sql = con.prepareStatement("select photo from blob_test WHERE rno = " +"+ IntNo +" );
catch (SQLException ex) {
//out.println("TEst�� ex");
System.out.println("TEst�� ex��");
//method prepareStatement(sting) not found in interface java.sql.connection
// sql.setInt( 1, rno );
try {
rs = sql.executeQuery();
catch (SQLException ex3) {
//out.println("TEst�� ex3");
System.out.println("TEst�� ex3");
System.out.println("TEst database operate ok��");
// out.println("TEst database operate ok��");
//��������������������
try {
if (rs.next()) {
buf = rs.getBytes(1);
in = rs.getBinaryStream("photo");
else {
buf = new byte[0];
}catch (Exception e){
//throw e;
response.reset();
//������image/jpeg������������������������
response.setContentType("image/bmp");
// ��bmp��jpeg
byte[] b = new byte[1024*1024];
int len;
while((len=in.read(b)) >0)
response.getOutputStream().write(b,0,len);
OutputStream out1 = response.getOutputStream();
out1.flush();
out1.write(buf);
in.close();
try {
rs.close();
catch (SQLException ex4) {
// out.println("<html>");
// out.println("<img src='http://192.168.0.1/examples/servlet/TestServlet1?PictNo="+IntNo+"'>");
// out.println("</html>");
out.println("<html>");
out.println("<head><title>TestServlet</title></head>");
out.println("<body bgcolor=\"#ffffff\">");
out.println("<p>The servlet has received a GET111111111. This is the reply.</p>");
out.println("</body></html>");
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>TestServlet</title></head>");
out.println("<body bgcolor=\"#ffffff\">");
out.println("<p>The servlet has received a POST. This is the reply.</p>");
out.println("</body></html>");
//Process the HTTP Put request
public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Process the HTTP Delete request
public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Clean up resources
public void destroy() {
hope u can get some thing from that -
Database access from session bean
Hello,
I have a stateless session bean which performs some complex
calculations, and also does some database access.
For the database access the bean class has a datasource as
follows:
public class TestBean implements SessionBean {
private DataSource ds_;
public void ejbCreate() {
getDataSources();
private void getDataSources() {
try {
Context ictx = new InitialContext();
ds_ = (DataSource)ictx.lookup("java:comp/env/jdbc/TestDB");
} catch (Exception e) {
e.printStackTrace();
throw new EJBException(e);
Now this class has a method (which is also in the remote interface)
calculateSomething(). This method constructs a number of other
objects that do the actual calculation, and one of these objects
does the actual database access. How would another object be able to
use the datasource that was constructed in the bean class?
I could pass the datasource reference to that object, but that would
break my encapsulation. This is because that object does not get
created directly by the bean object, but rather the way the objects
interact is something like A -> B -> C, where A is the TestBean, and
C is the object that does the DB access. If I passed the datasource,
I would need to make B aware of the datasource, which doesn't
seem good design, because B doesn't do any database access.
Alternatively I could do the lookup in class C, but that would
degrade the performance, as an object C gets created and destroyed
every time the calculateSomething() method is called.
A third option I have thought of, is to add a public method to the
bean that returns a connection. Whenever another object gets
created, a reference to the bean object will be passed along. Then,
if another object needs to do database access, it will call back
the bean to get a connection. This seems just as bad (if not worse)
than the first option.
Does anyone have an elegant solution for this situation? What is
the best practice of handling datasources when a bean class doesn't
do the database access itself? In all the examples I've seen so far,
all the functionality was in the session bean class, but again that
doesn't seem good OO design, and would result in a single huge class.
regards,
KostasThanks again to both for the replies. Here are my responses:
Yi Lin: Yes, I know that an entity bean would solve this problem, however it has been decided not to use entity beans so this is not my call (I think the reason entity beans are not allowed in this project is that they are considered risky: there are other applications that access the same database, so if the container caches entity bean data as you describe, then the users might get inconsistent results).
Gerard: Actually object B is the one that has the business logic and C is a peer object that only does database access and no calculaitons. For example B can be Customer, and C CustomerDB. This is why object B does not have any knowledge of datasources or connections. So my design does not appear to be that bad!
As far as the factory you propose is concerned, I cannot understand how this would solve my problem. In order to solve this situation the factory would need to be persistent, i.e. get created by the ejbCreate() method, and destroyed whenever the container decides to destroy the bean. There would be no point in object C creating the factory, as I would have the overhead of doing the JNDI lookup every time I create a C.
So the question remains the same: how would I pass a reference to the factory from A to C without making B aware of it? -
Database Access delays-how to improve upon that?
Hi friends,
I have this simple class,which takes in query and returns the results.I don't know why the database access is so slow,and if i try to add my driver load statements into the constructor the java class starts throwing "null pointer exception"(Java Class code given below)..I don't know much about connection pool,can u just have a look at this simple class,and tell me if there's anything on which i can improve upon and where to add the(*.close() statements).The same query runs instantly if i make a php program.Urgent help needed...please help me guys.
public class getResultSet{ private Connection con = null; private Statement st = null; private String dsn = "jdbc b2j:net:xxx"; private String uname = "xxx"; private String pwd = "xxx"; private String query = ""; ResultSet results; public void ResultS()throws Exception{ try{ Class.forName("com.ibm.db2.jcc.DB2Driver"); con = DriverManager.getConnection(dsn, uname, pwd); st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); } catch (SQLException e) { e.printStackTrace(); } } public ResultSet getResults(String query){ results = null; try{ results = st.executeQuery(query); } catch(SQLException sqle){ sqle.printStackTrace(); } return results; } }Some comments on the code
public class getResultSet{ // Class names should start with a capital letter and be nouns
private Connection con = null;
private Statement st = null; // Statements are transient and should probably not be a member variable
private String dsn = "jdbc b2j:net:xxx"; // dsn, user, pass should be final
private String uname = "xxx";
private String pwd = "xxx";
private String query = ""; // Seems you're not using this
ResultSet results; // This really shouldn't be declared here
public void ResultS()throws Exception{ // Method should start with a lower-case letter and be a verb/* The client code is supposed to call this, then the other method?
Very fragile. I'm guessing NullPointerExceptions occur if ResultS
is not called first. Have the other method call this one as necessary.
try{
Class.forName("com.ibm.db2.jcc.DB2Driver");
con = DriverManager.getConnection(dsn, uname,
uname, pwd);
st =
st =
=
con.createStatementResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ultSet.CONCUR_READ_ONLY);
catch (SQLException e) {
e.printStackTrace();
public ResultSet getResults(String query){
results = null;
try{
results = st.executeQuery(query);
catch(SQLException sqle){
sqle.printStackTrace();
return results; // It's a bad idea to return ResultSets as that leaves resources open
} // Where's the cleanup? You're leaving ResultSet, Statement, Connection open
>It is probably slow because opening connections takes a long time. You may or may not need a connection pool depending on your app. Perhaps you can just open a connection at the beginning and leave it open until your app finishes. That should reduce the overhead and still be very simple. -
Database access... what is the best approach
in a nutshell...
i have an applet that needs to access three data bases... currently i have it written and completed and working but the lag time on the database access is really slow so i am questioning my approach to the problem...
as a buisness rule we wanted to create classes to access the data through accessor mehtods from applications and appletts therfore standardizing our field name conventions, our methods and so on and so on...
so when the applett runs it creates an object for each class that access the database... when the user enters a valid "parcel number" the parcel is passed to the first class and the record is retrieved for database "A" and then it is passed to the next class and the supporting records are retrieved for data base "B" and it repeats the same concept for database "C".. so now i have the applet running and accessing the data through accessor methods through those objects...
each class makes the conection to the data base.. issues the sql, stores the results and closes the connection
i'll admit i am somewhat new to the java envirnoment so any help on concepts and approach would be most appreciated and useful
does this approach seem reasonable or am i letting my 15 years of procedural thinking get the best of me...
what would be the most effiecent way of doing this?
how much of a performance gain would i see if i threaded each one out on it's own thread and how would i do that?
the end product is going to be a county taxation system using browser technology as an inquiry system for public and general use and an application environment for inhouse data entry and use
creating seperate classes for each of the data basses seems ideal for what we want to do but maybe it is counterproductive considering the lag times.
i am using JDBC against an HP3000 image DataBaseWith the information given that is the only possible approach.
You could provide a middle layer which would then handle some of the interactions for you. For instance by keeping a connection pool.
Additionally if your databases are not actually distributed (and the same vendor) then you could do most of the work in a stored procedure. You could also do this if some of the data is relatively static and by using a server side replication process. -
Help...create database(access) using java
i had developed an java application that capture packet using Jpcap but i dont know how to keep the packet captured into database(access).i can save the packet captured in text file but not in database(access).i already had the database conectivity but i don't know how to insert the packet caputred in the table in access, is it using sql statement like INSERT INTO? or else?i realy don't know.can someone help me....?
i can save the packet captured in to text file but not in database(access).I guess that you wish to get a databse file with your data, not a simple insert sql question.
1. commercial solution: HXTT Access(http://www.hxtt.com/access.html), which supports create database, create table sql, and batch insert data from any JDBC driver.
2. free solution: jdbc-odbc bridge and dsn-less jdbc url, you need to prepare a blank mdb file with blank table, then copy that blank mdb file into new mdb file, then repeat insert sql for that new mdb file. -
Jsp database access using odbc - please help
Hi friends,
I�m trying a very simple database access program in jsp data base access using odbc. Odbc has to be used because thin driver or other drivers may not be available in every system of our college and as you know it's not that easy to make changes to those systems. My problem is so simple. I always get an exception in my program.
My jsp content is as simple as:
<%@ page import="java.lang.*,java.sql.*,java.io.*,registerbean" %>
<jsp:useBean id="db" class="registerbean" scope="session"/>
<%
String str="insert into reg values('" + db.getName() + "','" + db.getUname() + "','" + db.getPass() + "'," + db.getAge() + ",'" + db.getSex() + "','" + db.getAdd() + "','" + db.getUgcourse() + "','" + db.getUgqual() + "'," + db.getPer() + ",'" + db.getIadd() + "')";
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:yogaesh","scott","tiger");
Statement stmt=con.createStatement();
stmt.executeUpdate(str);
}catch(Exception e1){out.println(str);};
%>
the table reg has the structure:
Name Null? Type
CNAME VARCHAR2(20)
UNAME VARCHAR2(20)
CPSWD VARCHAR2(20)
CONFPASS VARCHAR2(20)
CAGE NUMBER
CSEX VARCHAR2(5)
CADD VARCHAR2(100)
COURSE NUMBER
CQUAL VARCHAR2(10)
CPER NUMBER
IADD VARCHAR2(100)
The registerbean.java file is as below: (This seems to work fine because I tried printing the values using <%= %> tag and it worked out fine and moreover the query string is intact.)
import java.io.*;
import java.util.*;
import java.lang.*;
public class registerbean
private String name,uname,pass,cpass,age,sex,add,ugcourse,ugqual,per,iadd,otherugqual,ccode;
public void setName(String a)
name=a;
public void setUname(String a)
uname=a;
public void setPass(String a)
pass=a;
public void setCpass(String a)
cpass=a;
public void setAge(String a)
age=a;
public void setSex(String a)
sex=a;
public void setAdd(String a)
add=a;
public void setOtherugqual(String a)
otherugqual=a;
public void setCcode(String a)
ccode=a;
public void setUgcourse(String a)
ugcourse=a;
public void setUgqual(String a)
ugqual=a;
public void setPer(String a)
per=a;
public void setIadd(String a)
iadd=a;
public String getName()
return(name);
public String getUname()
return(uname);
public String getPass()
return(pass);
public String getCpass()
return(cpass);
public String getAge()
return(age);
public String getCcode()
return(ccode);
public String getSex()
return(sex);
public String getAdd()
return(add);
public String getUgcourse()
return(ugcourse);
public String getUgqual()
return(ugqual);
public String getPer()
return(per);
public String getIadd()
return(iadd);
public String getOtherugqual()
return(otherugqual);
I initially thought the problem was with str but then str seems to be perfect and I get a string of the form �insert into reg values('c','c','c',98,'Male','c','B.Tech, Applied Artificial Neural Networks','HSC',9898,'h')� which I verified through a javascript debugger. The session scope used is to get values through the db bean from another jsp file. The problem is in the executeUpdate() line of this code. I even tried changing the updation table, but in vain. What could be done to rectify this? Please help me out and please do remember that I have no option but to use odbc.
Thanks in advance.
R. Yogaesh.I didn't verify the type of exception and i'm now going to do that, but then when the string is as perfect as needed, what is the need for a prepared statement? What is the basic difference between the two? And basically what is the problem with this piece of code which creates an exception? Please reply as soon as possible.
Thankyou very much.
R. Yogaesh. -
Servlet with Database Access!!!
Hi !!!!
I have deployed HelloServlet with Oracle Application Server 4.0.8.1.
Now I want to connect from Servlet to Oracle8i 8.1.5.
But, when I try to deploy a Servlet with Database Access, I receive the next:
"Get operation not allowed"
The URL used is:
http://host.domain:port/virtual_path/class_name
The servlet was compiled using the Sun's jdk from command line. There wasn't compilation errors.
I run a simple application with database access from command line without problems.
The drivers and JDBC libraries are operating for this simple application.
Any help will be appreciated.
Many thanks
SergioIf you are running OAS 4.0.8.1 and Oracle 8.1.5 on the same machine then this could be the problem. These products are not certified to run on the same machine as they give a path conflict.
Hope this helps.
Maybe you are looking for
-
"save as" work differently in menue and batch
If I save in Illustrator CS4 a EPS File from the menue with "save as" and then I place the file in InDesign CS4 and adjust it proportionally to the frame it works fine. The object is shortly to the frame. The same file with the batch option (New Acti
-
Best design for an Airport network in an odd house?
I live in a large 3 storey house (wooden). My 9,000 kb/s cable internet comes in at level 3 into my Airport Extreme (n/b/g/a) base station. My new iMac sits right next to the base station and works fine, clocking pretty much full speed when I run tho
-
Collaborator on Document Level vs. Class Level Access
Hi Guys, I am wondering what happens when you add a user as a collaborator / reviewer to a document that has not been given authorization on class level, ie. the user has no access to auctions but I am adding him/ her to an auction as a collaborator?
-
More than 2 OCR files and 3 VOTE files
Is it possible to add more than 2 OCR files and more than 3 VOTE files in 2-node RAC ?
-
[Solved] Failure building cairo-xcb
I tried to install "awesome" window manager, Im quite interested in it, and it's dependency is cairo-xcb. I downloaded cairo-xcb from AUR but I cant install due to some error: [broi@broi-Archlinux cairo-xcb]$ makepkg -csi ==> Making package: cairo-xc