Setting tomcat to use jdbc
I have created a new development directory say
c:\servlets-jsp
under
It works under this directory but I does not allow me to use jdbc-odbc
How can I set it up in tomcat to do so?
I just got mine to work yesterday, so may be I can help.
Now, when you say it does not allow you to use jdbc:odbc, are you talking about the jdbc:oracle:thin?
Similar Messages
-
Installing Log4J in Tomcat and using JDBC to log errors
Has anyone figured out how to install Log4J in Tomcat and use the Log4J JDBC functionality?
I have log4j.jar in CATALINA_HOME/common/lib.
I also have log4j.properties is in CATALINA_HOME/common/classes
Then when I start Tomcat I get the following error:
[main] DEBUG org.apache.commons.digester.Digester - addRuleSet() with no namespace URI
is it something to do w/ the log4j.properties file? do i have to use a xml format or is it ok to use .properties format?
-KarthikI would say you have something wrong in your log4j properties file.
properties format is fine, but I suspect something in there is not quite right.
Try starting with a simple example one, see if it works, and then try adding your own config based on that one.
Good luck,
evnafets -
Help: Connecting Tomcat to CA-IDMS Using JDBC Type 4 Drivers (JNDI)
Hi there,
I have a rather interesting / complex problem......creating a connection to CA-IDMS from Tomcat using JDBC type 4 drivers (CA provide the type 4 driver).
We have a zSeries 9 IBM mainframe running CA-IDMS r16.1, and I need to connect to the IDMS from Tomcat (running on Linux) using the JDBC Type 4 drivers provided by CA.
At this stage I am struggling with the actual setup and configuration of Tomcats server.xml and web.xml files. These are the files where the JDBC configuration is set (I think). I have to setup the CA-IDMS part of the configuration, but that is a different problem. Basically there is a TCP/IP listener on the IDMS, waiting for incoming connections from the JDBC type 4 driver.
I set up a Tomcat to MySQL connection using MySQL Connector / J, which is a similar kind of process to what I am trying to achieve with IDMS. MySQL connector / J came with a jar file which is placed in Tomcats lib folder, and then the JDBC setup for the web application is created in Tomcat's server.xml and web.xml files. You can then connect to the MySQL database using JSP and the configured JDBC driver / connection. The CA-IDMS Server comes with an idmsjdbc.jar file, which I think is the JDBC typr 4 driver. I think it needs to be placed in the Tomcat /lib folder, but I dont know how to set up the configuration.
There is a JDBC DriverManager which allows JDBC drivers to connect to CA-IDMS. The DriverManager recognises the following syntax:
jdbc:idms://hostname:port/database
This allows the JDBC driver running within Tomcat to connect to the IDMS which is running on the IDM mainframe. CA IDMS r16 supports direct connections from the Type 4 JDBC driver to the Central Version on IDMS. "hostname" is the DNS name or IP address of the machine where the CV is running, and "port" is the IP port that was specified for the listener PTERM (setup on the IDMS side).
There is a caidms.properties file for the JDBC driver, which is used to specify user ID, password, and optional accounting information. It can also be used to specify physical connection information, allowing an application to connect to a CA-IDMS database without requiring the definition of an ODBC style data source. However, I dont know where to place this file within the Tomcat setup.
There is also an IdmsDataSource class. I dont know where to configure this or how to set it up; the CA-IDMS Server manual states the following:
This class implements the JDBC DataSource interface. It is used with an application server (Tomcat) providing Java Naming and Directory Interface (JNDI) naming service to establish a connection to a CA IDMS database. IdmsDataSource properties conform to the Java Beans naming conventions and are implicitly defined by public setter and getter methods. For example, the description property, which is required for all DataSource implementations, is set using the setDescription(String) method. The application server may use the java.lang.reflection methods to discover DataSource properties and provide an interface to set them, or may simply require that they are defined in some configuration file. IdmsDataSource properties are used to specify the connection parameters. These properties are the equivalent of the DriverPropertyInfo attributes described in the previous section and can be used to completely define the parameters needed to connect to a database. Like a URL, an IdmsDataSource object can also reference an ODBC style data source name, where the connection parameters are defined in the configuration file on Linux.
Is there anyone that can try to point me in the right direction to setting up the JDBC connection? I am totally new to Java and so the instructions are not making much sense at the moment. Any help, hints, tips ..anything will be greatly appreciated as I have just hit a brick wall here. I can't find much to do with setting up the CA-IDMS Server JDBC type 4 driver online either....if anyone can point me to some resources that would also be extremely useful.
Kind regards
JpYou say you've managed to get the JDBC driver working
in an application but not in a JSP. You also say that
the error you get is
"com.microsoft.jdbc.sqlserver.SQLServerDriver".
I'd be willing to bet that the exception that you have
got is a ClassNotFoundException. I.E. your application
server hasn't found the JDBC driver classes. The
application server probably doesn't use your current
CLASSPATH to look for classes. It will be setup within
the application server in some way and you'll need to
check your app server documentation to see how it is
done.
Try replacing
e.printStackTrace();with
e.printStackTrace(out);to get a full stack trace of your error.
ColTried it. Got this error when I tried to run the JSP.
Incompatible type for method. Can't convert javax.servlet.jsp.JspWriter to java.io.PrintWriter.
e.printStackTrace(out);
I'm currently using Apache Tomcat 4.0.3 as my JSP/Servlet Container.
I'm also using Type 4 MS SQL Server 2000 JDBC driver version 2.0 on my NT4.0 Server.
Do I need to set my JDBC driver in my container? if so, how do I do that? -
Exception report when using tomcat 5 with JDBC
i followed this guide to setup the JDBC with my TOMCAT 5
http://jakarta.apache.org/tomcat/tomcat-5.0-doc/jndi-datasource-examples-howto.html#Database%20Connection%20Pool%20(DBCP)%20Configurations
but i seem to get this error
exception
javax.servlet.ServletException: Unable to get connection, DataSource invalid: "org.apache.commons.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'"
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:846)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:779)
org.apache.jsp.SID.test_jsp._jspService(test_jsp.java:81)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
root cause
javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "org.apache.commons.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'"
org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.getConnection(QueryTagSupport.java:276)
org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.doStartTag(QueryTagSupport.java:159)
org.apache.jsp.SID.test_jsp._jspx_meth_sql_query_0(test_jsp.java:100)
org.apache.jsp.SID.test_jsp._jspService(test_jsp.java:58)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
i can compile *.java and run them when they need the jdbc drivers to interact with mysql 5 database.
This is my server.xml
<!-- Example Server Configuration File -->
<!-- Note that component elements are nested corresponding to their
parent-child relationships with each other -->
<!-- A "Server" is a singleton element that represents the entire JVM,
which may contain one or more "Service" instances. The Server
listens for a shutdown command on the indicated port.
Note: A "Server" is not itself a "Container", so you may not
define subcomponents such as "Valves" or "Loggers" at this level.
-->
<Server port="8005" shutdown="SHUTDOWN" debug="0">
<!-- Comment these entries out to disable JMX MBeans support -->
<!-- You may also configure custom components (e.g. Valves/Realms) by
including your own mbean-descriptor file(s), and setting the
"descriptors" attribute to point to a ';' seperated list of paths
(in the ClassLoader sense) of files to add to the default list.
e.g. descriptors="/com/myfirm/mypackage/mbean-descriptor.xml"
-->
<Listener className="org.apache.catalina.mbeans.ServerLifecycleListener"
debug="0"/>
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"
debug="0"/>
<!-- Global JNDI resources -->
<GlobalNamingResources>
<!-- Test entry for demonstration purposes -->
<Environment name="simpleValue" type="java.lang.Integer" value="30"/>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users -->
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved">
</Resource>
<ResourceParams name="UserDatabase">
<parameter>
<name>factory</name>
<value>org.apache.catalina.users.MemoryUserDatabaseFactory</value>
</parameter>
<parameter>
<name>pathname</name>
<value>conf/tomcat-users.xml</value>
</parameter>
</ResourceParams>
</GlobalNamingResources>
<!-- A "Service" is a collection of one or more "Connectors" that share
a single "Container" (and therefore the web applications visible
within that Container). Normally, that Container is an "Engine",
but this is not required.
Note: A "Service" is not itself a "Container", so you may not
define subcomponents such as "Valves" or "Loggers" at this level.
-->
<!-- Define the Tomcat Stand-Alone Service -->
<Service name="Catalina">
<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Each Connector passes requests on to the
associated "Container" (normally an Engine) for processing.
By default, a non-SSL HTTP/1.1 Connector is established on port 8080.
You can also enable an SSL HTTP/1.1 Connector on port 8443 by
following the instructions below and uncommenting the second Connector
entry. SSL support requires the following steps (see the SSL Config
HOWTO in the Tomcat 5 documentation bundle for more detailed
instructions):
* If your JDK version 1.3 or prior, download and install JSSE 1.0.2 or
later, and put the JAR files into "$JAVA_HOME/jre/lib/ext".
* Execute:
%JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA (Windows)
$JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA (Unix)
with a password value of "changeit" for both the certificate and
the keystore itself.
By default, DNS lookups are enabled when a web application calls
request.getRemoteHost(). This can have an adverse impact on
performance, so you can disable it by setting the
"enableLookups" attribute to "false". When DNS lookups are disabled,
request.getRemoteHost() will return the String version of the
IP address of the remote client.
-->
<!-- Define a non-SSL Coyote HTTP/1.1 Connector on port 8080 -->
<Connector port="8080"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
debug="0" connectionTimeout="20000"
disableUploadTimeout="true" />
<!-- Note : To disable connection timeouts, set connectionTimeout value
to 0 -->
<!-- Note : To use gzip compression you could set the following properties :
compression="on"
compressionMinSize="2048"
noCompressionUserAgents="gozilla, traviata"
compressableMimeType="text/html,text/xml"
-->
<!-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 -->
<!--
<Connector port="8443"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" disableUploadTimeout="true"
acceptCount="100" debug="0" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
-->
<!-- Define a Coyote/JK2 AJP 1.3 Connector on port 8009 -->
<Connector port="8009"
enableLookups="false" redirectPort="8443" debug="0"
protocol="AJP/1.3" />
<!-- Define a Proxied HTTP/1.1 Connector on port 8082 -->
<!-- See proxy documentation for more information about using this. -->
<!--
<Connector port="8082"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false"
acceptCount="100" debug="0" connectionTimeout="20000"
proxyPort="80" disableUploadTimeout="true" />
-->
<!-- An Engine represents the entry point (within Catalina) that processes
every request. The Engine implementation for Tomcat stand alone
analyzes the HTTP headers included with the request, and passes them
on to the appropriate Host (virtual host). -->
<!-- You should set jvmRoute to support load-balancing via JK/JK2 ie :
<Engine name="Standalone" defaultHost="localhost" debug="0" jvmRoute="jvm1">
-->
<!-- Define the top level container in our container hierarchy -->
<Engine name="Catalina" defaultHost="localhost" debug="0">
<!-- The request dumper valve dumps useful debugging information about
the request headers and cookies that were received, and the response
headers and cookies that were sent, for all requests received by
this instance of Tomcat. If you care only about requests to a
particular virtual host, or a particular application, nest this
element inside the corresponding <Host> or <Context> entry instead.
For a similar mechanism that is portable to all Servlet 2.4
containers, check out the "RequestDumperFilter" Filter in the
example application (the source for this filter may be found in
"$CATALINA_HOME/webapps/examples/WEB-INF/classes/filters").
Request dumping is disabled by default. Uncomment the following
element to enable it. -->
<!--
<Valve className="org.apache.catalina.valves.RequestDumperValve"/>
-->
<!-- Global logger unless overridden at lower levels -->
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="catalina_log." suffix=".txt"
timestamp="true"/>
<!-- Because this Realm is here, an instance will be shared globally -->
<!-- This Realm uses the UserDatabase configured in the global JNDI
resources under the key "UserDatabase". Any edits
that are performed against this UserDatabase are immediately
available for use by the Realm. -->
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
debug="0" resourceName="UserDatabase"/>
<!-- Comment out the old realm but leave here for now in case we
need to go back quickly -->
<!--
<Realm className="org.apache.catalina.realm.MemoryRealm" />
-->
<!-- Replace the above Realm with one of the following to get a Realm
stored in a database and accessed via JDBC -->
<!--
<Realm className="org.apache.catalina.realm.JDBCRealm" debug="99"
driverName="org.gjt.mm.mysql.Driver"
connectionURL="jdbc:mysql://localhost/authority"
connectionName="test" connectionPassword="test"
userTable="users" userNameCol="user_name" userCredCol="user_pass"
userRoleTable="user_roles" roleNameCol="role_name" />
-->
<!--
<Realm className="org.apache.catalina.realm.JDBCRealm" debug="99"
driverName="oracle.jdbc.driver.OracleDriver"
connectionURL="jdbc:oracle:thin:@ntserver:1521:ORCL"
connectionName="scott" connectionPassword="tiger"
userTable="users" userNameCol="user_name" userCredCol="user_pass"
userRoleTable="user_roles" roleNameCol="role_name" />
-->
<!--
<Realm className="org.apache.catalina.realm.JDBCRealm" debug="99"
driverName="sun.jdbc.odbc.JdbcOdbcDriver"
connectionURL="jdbc:odbc:CATALINA"
userTable="users" userNameCol="user_name" userCredCol="user_pass"
userRoleTable="user_roles" roleNameCol="role_name" />
-->
<!-- Define the default virtual host
Note: XML Schema validation will not work with Xerces 2.2.
-->
<Host name="localhost" debug="0" appBase="webapps"
unpackWARs="true" autoDeploy="true"
xmlValidation="false" xmlNamespaceAware="false">
<!-- Defines a cluster for this node,
By defining this element, means that every manager will be changed.
So when running a cluster, only make sure that you have webapps in there
that need to be clustered and remove the other ones.
A cluster has the following parameters:
className = the fully qualified name of the cluster class
name = a descriptive name for your cluster, can be anything
debug = the debug level, higher means more output
mcastAddr = the multicast address, has to be the same for all the nodes
mcastPort = the multicast port, has to be the same for all the nodes
mcastBindAddr = bind the multicast socket to a specific address
mcastTTL = the multicast TTL if you want to limit your broadcast
mcastSoTimeout = the multicast readtimeout
mcastFrequency = the number of milliseconds in between sending a "I'm alive" heartbeat
mcastDropTime = the number a milliseconds before a node is considered "dead" if no heartbeat is received
tcpThreadCount = the number of threads to handle incoming replication requests, optimal would be the same amount of threads as nodes
tcpListenAddress = the listen address (bind address) for TCP cluster request on this host,
in case of multiple ethernet cards.
auto means that address becomes
InetAddress.getLocalHost().getHostAddress()
tcpListenPort = the tcp listen port
tcpSelectorTimeout = the timeout (ms) for the Selector.select() method in case the OS
has a wakup bug in java.nio. Set to 0 for no timeout
printToScreen = true means that managers will also print to std.out
expireSessionsOnShutdown = true means that
useDirtyFlag = true means that we only replicate a session after setAttribute,removeAttribute has been called.
false means to replicate the session after each request.
false means that replication would work for the following piece of code:
<%
HashMap map = (HashMap)session.getAttribute("map");
map.put("key","value");
%>
replicationMode = can be either 'pooled', 'synchronous' or 'asynchronous'.
* Pooled means that the replication happens using several sockets in a synchronous way. Ie, the data gets replicated, then the request return. This is the same as the 'synchronous' setting except it uses a pool of sockets, hence it is multithreaded. This is the fastest and safest configuration. To use this, also increase the nr of tcp threads that you have dealing with replication.
* Synchronous means that the thread that executes the request, is also the
thread the replicates the data to the other nodes, and will not return until all
nodes have received the information.
* Asynchronous means that there is a specific 'sender' thread for each cluster node,
so the request thread will queue the replication request into a "smart" queue,
and then return to the client.
The "smart" queue is a queue where when a session is added to the queue, and the same session
already exists in the queue from a previous request, that session will be replaced
in the queue instead of replicating two requests. This almost never happens, unless there is a
large network delay.
-->
<!--
When configuring for clustering, you also add in a valve to catch all the requests
coming in, at the end of the request, the session may or may not be replicated.
A session is replicated if and only if all the conditions are met:
1. useDirtyFlag is true or setAttribute or removeAttribute has been called AND
2. a session exists (has been created)
3. the request is not trapped by the "filter" attribute
The filter attribute is to filter out requests that could not modify the session,
hence we don't replicate the session after the end of this request.
The filter is negative, ie, anything you put in the filter, you mean to filter out,
ie, no replication will be done on requests that match one of the filters.
The filter attribute is delimited by ;, so you can't escape out ; even if you wanted to.
filter=".*\.gif;.*\.js;" means that we will not replicate the session after requests with the URI
ending with .gif and .js are intercepted.
The deployer element can be used to deploy apps cluster wide.
Currently the deployment only deploys/undeploys to working members in the cluster
so no WARs are copied upons startup of a broken node.
The deployer watches a directory (watchDir) for WAR files when watchEnabled="true"
When a new war file is added the war gets deployed to the local instance,
and then deployed to the other instances in the cluster.
When a war file is deleted from the watchDir the war is undeployed locally
and cluster wide
-->
<!--
<Cluster className="org.apache.catalina.cluster.tcp.SimpleTcpCluster"
managerClassName="org.apache.catalina.cluster.session.DeltaManager"
expireSessionsOnShutdown="false"
useDirtyFlag="true">
<Membership
className="org.apache.catalina.cluster.mcast.McastService"
mcastAddr="228.0.0.4"
mcastPort="45564"
mcastFrequency="500"
mcastDropTime="3000"/>
<Receiver
className="org.apache.catalina.cluster.tcp.ReplicationListener"
tcpListenAddress="auto"
tcpListenPort="4001"
tcpSelectorTimeout="100"
tcpThreadCount="6"/>
<Sender
className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
replicationMode="pooled"/>
<Valve className="org.apache.catalina.cluster.tcp.ReplicationValve"
filter=".*\.gif;.*\.js;.*\.jpg;.*\.htm;.*\.html;.*\.txt;"/>
<Deployer className="org.apache.catalina.cluster.deploy.FarmWarDeployer"
tempDir="/tmp/war-temp/"
deployDir="/tmp/war-deploy/"
watchDir="/tmp/war-listen/"
watchEnabled="false"/>
</Cluster>
-->
<!-- Normally, users must authenticate themselves to each web app
individually. Uncomment the following entry if you would like
a user to be authenticated the first time they encounter a
resource protected by a security constraint, and then have that
user identity maintained across all web applications contained
in this virtual host. -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn"
debug="0"/>
-->
<!-- Access log processes all requests for this virtual host. By
default, log files are created in the "logs" directory relative to
$CATALINA_HOME. If you wish, you can specify a different
directory with the "directory" attribute. Specify either a relative
(to $CATALINA_HOME) or absolute path to the desired directory.
-->
<!--
<Valve className="org.apache.catalina.valves.AccessLogValve"
directory="logs" prefix="localhost_access_log." suffix=".txt"
pattern="common" resolveHosts="false"/>
-->
<!-- Logger shared by all Contexts related to this virtual host. By
default (when using FileLogger), log files are created in the "logs"
directory relative to $CATALINA_HOME. If you wish, you can specify
a different directory with the "directory" attribute. Specify either a
relative (to $CATALINA_HOME) or absolute path to the desired
directory.-->
<Logger className="org.apache.catalina.logger.FileLogger"
directory="logs" prefix="localhost_log." suffix=".txt"
timestamp="true"/>
<Context path="/testdb" docBase="APACHE_DIR/htdocs/testdb"
debug="5" reloadable="true" crossContext="true">
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="localhost_DBTest_log." suffix=".txt"
timestamp="true"/>
<Resource name="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/TestDB">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<!-- Maximum number of dB connections in pool. Make sure you
configure your mysqld max_connections large enough to handle
all of your db connections. Set to 0 for no limit.
-->
<parameter>
<name>maxActive</name>
<value>10</value>
</parameter>
<!-- Maximum number of idle dB connections to retain in pool.
Set to 0 for no limit.
-->
<parameter>
<name>maxIdle</name>
<value>5</value>
</parameter>
<!-- Maximum time to wait for a dB connection to become available
in ms, in this example 10 seconds. An Exception is thrown if
this timeout is exceeded. Set to -1 to wait indefinitely.
-->
<parameter>
<name>maxWait</name>
<value>10000</value>
</parameter>
<!-- MySQL dB username and password for dB connections -->
<parameter>
<name>username</name>
<value>test</value>
</parameter>
<parameter>
<name>password</name>
<value>testpwd</value>
</parameter>
<!-- Class name for mm.mysql JDBC driver -->
<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>
<!-- The JDBC connection url for connecting to your MySQL dB.
The autoReconnect=true argument to the url makes sure that the
mm.mysql JDBC Driver will automatically reconnect if mysqld closed the
connection. mysqld by default closes idle connections after 8 hours.
-->
<parameter>
<name>url</name>
<value>jdbc:mysql://localhost/testdb?autoReconnect=true</value>
</parameter>
</ResourceParams>
</Context>
</Host>
</Engine>
</Service>
</Server>You haven't added a resource reference for your web application that gives the application a local name for the global resource "UserDatabase".
-
Memory Leak when TOMCAT connects to Oracle 10g RAC using JDBC Thin driver.
We had experienced Memory leak when a Oracle 10g (10.2.0.3) RAC node was evicted. TOMCAT app server is connecting to the Oracle 10g RAC database instances using JDBC 10.2.0.3 thin driver.
Anyone had similar experience?
Any ideas? Any bugs reported/fixed?
Thanks,
RajIf you're doing XA, we absolutely do not support
driver-level load-balancing OR failover. Use neither.
For non-XA, you can use driver-level failover. For
non-XA, you could set load-balancing, but it won't
help because we get connections from the driver,
and keep them indefinitely, so the driver never gets
the chance to affect which connections the pool
uses after that. -
Set target fileds from source fields using JDBC lookUp
hello :
advance thanks for reading below and i am new to java
how to to set the two taget fileds T1 and T2 from source field S1 using jdbc look up .Here is the code and its giving syntax error . set T1 to approver1 and T2 to approver2
I copied the code from blog 2219
How to map to two target fileds ??
Is something wrong with the query ?
/people/siva.maranani/blog/2005/08/23/lookup146s-in-xi-made-simpler
>>>>>>>>I defined Argument a(i am passing S1) Result result
>>>Here is the code :
//write your code here
String Query = " ";
Channel channel = null;
DataBaseAccessor accessor = null;
DataBaseResult resultSet = null;
// Build the Query String
Query = "Select (approver1,approver2) from Emp where loginid = ' " + a[0] + " ' '';
try{
//Determine a channel, as created in the Configuration
channel = LookupService.getChannel("SQL99","jdbc_cc1");
//Get a system accessor for the channel. As the call is being made to an DB, an //DatabaseAccessor is obtained.
accessor = LookupService.getDataBaseAccessor(channel);
//Execute Query and get the values in resultset
resultSet = accessor.execute(Query);
for(Iterator rows = resultSet.getRows();rows.hasNext();){
Map rowMap = (Map)rows.next();
result.addValue((String)rowMap.get("(approver1"));
//result.addValue((String)rowMap.get("approver2"));
catch(Exception ex){
result.addValue(ex.getMessage())
finally{
try{
if (accessor!=null) accessor.close();
catch(Exception e){
result.addValue(e.getMessage())
thankyou sdn:hi kumar,
every statment in java should end with a semicolon... and 2 catch statments in the code given in blog(that you mentioned) are with missing semicolons at the end of the statments... just include semicolons at the end of these 2 catch staments and your code should work properly without any syntax error...
catch(Exception ex){
result.addValue(ex.getMessage());
finally{
try{
if (accessor!=null) accessor.close();
catch(Exception e){
result.addValue(e.getMessage());
Regards,
JP -
Help setting Parameters using JDBC and Bind Variables for Oracle List
I fully understand the concept of using Bind Variables when using JDBC to avoid hard parses everytime my SQL statement is executed when only a certain value changes. For example, perhaps I have the following statement:
PreparedStatement ps = con.prepareStatement("select salary from employees where employee_id = ?");
I would then set the value of the question mark (the first and in this case only parameter) using:
ps.getStmt().setString(1,empId1);
That is assuming I have the variable empId1 populated with what I want. Anyway, my question has to do with Oracle lists. In other words, if I am just executing the statement against the db, it might look like:
select salary from employees where employee_id in ('123','456','789');
I still want to use bind variables and I can do it in JDBC with something like:
select salary from employees where employee_id in ('123','456','789');
ps.getStmt().setString(1,empId1);
ps.getStmt().setString(2,empId2);
ps.getStmt().setString(3,empId3);
BUT, what if I just want to construct my list of ids upfront as a string and do something like:
select salary from employees where employee_id in (?)
ps.getStmt().setString(1,listOfEmpIds);where listOfEmpIds would look something like '123','456','789'.
That's what I want to do but it doesn't work. It would be treating the list as a single parameter as opposed to lots of individual parameters. Can someone please tell me the syntax for this if it is possible? I have tried where XX in (?) and where XX in ? (and the string I substitute has the parenthesis in it), but neither work.
Thank you for your help.I always build the list myself.
You could, however, pass the list as a varchar to a stored proc and then have the stored proc parse (or dynamically execute) using it.
The second method might even be faster although I would suspect that is only going to be the case if the list is very large. Or it might not. -
How can I see KSC5602 character set using JDBC thin driver
After I change character set from USASCII7 to KO16KSC5601, I
cannot see korean from the clients
using JDBC thin driver.
But, I can see korean clearly using sqlplus at serer, or
application using SQLNet.
I use Oracle Enterprise Server 8.0.4.1.0, jdbc thin driver
8.0.4.0.6 on Windows 98. I read that all bugs realated
to multibyte language are fixed in Oracle8. What can I do to
solve this problem?
PS.server: Oracle 8.0.4.1 on Digital Unix 4.0b, client: jdk1.1.8
on Windows98. I used the command.
nullThe easiest thing to do is download it as an archive with your applet.
Otherwise, you have to have the files on every client machine.
For netscape, put the classes111.jar in the java classes folder typically:
c:\ProgramFiles\Netscape\Communicator\Program\java\classes.
I'd expect that IE would be setup in a similar way. -
Using JDBC Persistent Manager for Tomcat across multiple Servers
Sorry if I word this question incorrectly, but I hope you can get the gist of it. Basically, I have a web application that will be running on 2 different machines. When too many users are on one machine, they are switched over to another machine (load balancing). If I use JDBC (or file) Persistance Manager to store sessions, what happens when a user is switched between machines? If both machines use the same settings for the Persistance Manager, when a user has just been moved to a new machine, will it be able to load the session from the DB? (since it should have its sessionID). If you can not do this, is there a way to do it?
Thanks!Sorry if I word this question incorrectly, but I hope
you can get the gist of it. Basically, I have a web
application that will be running on 2 different
machines. When too many users are on one machine,
they are switched over to another machine (load
balancing). If I use JDBC (or file) Persistance
Manager to store sessions, what happens when a user is
switched between machines? If both machines use the
same settings for the Persistance Manager, when a user
has just been moved to a new machine, will it be able
to load the session from the DB? (since it should
have its sessionID). If you can not do this, is
there a way to do it?
Thanks!Session ids are unique and cannot be transferred between different servers... Wise web servers supports load balancing and should be able to transfer/store session without your special code. If you still keen to write transfer code yourself you have to:
1) Store not only session id, but also all content of session (including some virtual (your) session id
2) Transfer (i.e. create a copy) stored session content to another machine
Paul -
How to use JDBC Connection Pools in a standalone application?
Hi, there,
I have a question about how to use JDBC Connection Pools in an application. I know well about connection pool itself, but I am not quite sure how to keep the pool management object alive all the time to avoid being destroyed by garbage collection.
for example, at the website: http://www.developer.com/java/other/article.php/626291, there is a simple connection pool implementation. there are three classes:JDBCConnection, the application's gateway to the database; JDBCConnectionImpl, the real class/object to provide connection; and JDBCPool, the management class to manage connection pool composed by JDBCConnectionImpl. JDBCPool is designed by Singleton pattern to make sure only one instance. supposing there is only one client to use connection for many times, I guess it's ok because this client first needs instantiate JDBCPool and JDBCConnectionImpl and then will hold the reference to JDBCPool all the time. but how about many clients want to use this JDBCPool? supposing client1 finishes using JDBCPool and quits, then JDBCPool will be destroyed by garbage collection since there is no reference to it, also all the connections of JDBCConnectionImpl in this pool will be destroyed too. that means the next client needs recreate pool and connections! so my question is that if there is a way to keep pool management instance alive all the time to provide connection to any client at any time. I guess maybe I can set the pool management class as daemon thread to solve this problem, but I am not quite sure. besides, there is some other problems about daemon thread, for example, how to make sure there is only one daemon instance? how to quit it gracefully? because once the whole application quits, the daemon thread also quits by force. in that case, all the connections in the pool won't get chance to close.
I know there is another solution by JNDI if we develop servlet application. Tomcat provides an easy way to setup JNDI database pooling source that is available to JSP and Servlet. but how about a standalone application? I mean there is no JNDI service provider. it seems a good solution to combine Commons DBCP with JNID or Apache's Naming (http://jakarta.apache.org/commons/dbcp/index.html). but still, I don't know how to keep pool management instance alive all the time. once we create a JNDI enviroment or naming, if it will save in the memory automatically all the time? or we must implement it as a daemon thread?
any hint will be great apprieciated!
SamTo my knoledge the pool management instance stays alive as long as the pool is alive. What you have to figure out is how to keep a reference to it if you need to later access it.
-
Using JDBC to update nvarchar (foreiegn character data)
We have an application that updates tables in Oracle with foreign character data. The database character set is not UTF-16 but nvarchar columns are set to be nvarchar.
The application is working correctly in our development environment (using ORAOLEDB to connect to the server with the NDATATYPE value set to true). The development env is Eclipse/Tomcat 5.5/JRE 1.4
Our production environment is Weblogic using JDBC. In this environment we cannot correctly update our database with ???? written to the database.
What can we do to fix this issue?
TksMark,
I believe Kuassi Mensah has an example of this in his book.
Sorry but I don't have my copy handy now.
Just search for his threads in the forum archives: Not just this one.
Try the JDBC forum and the Oracle database JVM forum.
Basically you can load the DB2 JDBC driver into Oracle database and then use a java stored procedure to get the data.
Good Luck,
Avi. -
How can i put a file into blob using jdbc !?
Hi
i tried to put a file into blob , but got a problem.....
My environment:windows 2000pro,JBuilder 5.0 enterprise,oracle 8.1.6,(not install oracle jdbc driver )
a part of program(my program is very uglily,if anyone want,later i paste it ba....~_~)
//Statement stmt2=null;
//Resultset rs2;
//opa1 is the blob data
void saveBlobTableToDisk(Connection con) {
try {
stmt2=con.createStatement();
sqlStr2="SELECT * FROM emp3 where id=1004";
rs2=stmt2.executeQuery(sqlStr2);
while (rs2.next()) {
Blob aBlob=rs2.getBlob("opa1");
i got the exception :
" null
java.lang.UnsupportedOperationException
at sun.jdbc.odbc.JdbcOdbcResultSet.getBlob(JdbcOdbcResultSet.java:4174)
at test3.Frame1.saveBlobTableToDisk(Frame1.java:48)
at test3.Frame1.<init>(Frame1.java:26)
at test3.Application1.<init>(Application1.java:5)
at test3.Application1.main(Application1.java:8) "
and the windows pop up a messagebox said that(about) my memory "0x09af007f" could not read, error in javaw.exe .
Later i used (ResultSet)getBinaryStream() to solve it. but getBinaryStream() only return a InputStream,so that i can make blob to a file,but i can't make a file to blob using jdbc.....
I am very stupid that installing sun java, oracle jdbc driver etc....(because i must set a lot of thing such as classpath,java_home etc), Can i only use JBuilder to do that ?
Or i must install oracle jdbc driver ?
Thanks.
D.T.My guess here is that Sun's JDBC-ODBC bridge doesn't handle the BLOB datatype. Most ODBC drivers don't support that datatype, so I wouldn't expect the bridge to.
Is there a reason that you can't use the Oracle driver?
Justin -
Problem using Jdbc-Odbc Bridge
Hi,
I am using Java 2 SDK and I am trying to access MS Access database on my machine using Jdbc-Odbc bridge. I have set up the DSN in ODBC. But I get the following error when I run my program -
'No Suitable Driver'
Here's my code snippet-
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
String dsn = "jdbc:odbc:DriverInfoDB";
Connection con = DriverManager.getConnection(dsn,"","");
con.setAutoCommit(false);
Statement stmt;
String query = null; // SQL select string
ResultSet rs; // SQL query results
stmt = con.createStatement();
.....etc etc...
Where is the error in this code??
Help Needed!!
Thanks
Vivek.try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(dsn,"guest","guest");
OR DriverManager.getConnection(dsn);
System.out.println("Conection's opened");
catch(ClassNotFoundException cnfe)
System.err.println(cnfe);
catch(SQLException sqle)
System.err.println(sqle);
try that code and double check you DSN Name . it's a good practice to greate a system DSN.
i hope that helps.
FEEL FREE TO ASK. WON'T BITE U
ABDUL -
Can't read special characters in an excel file using JDBC
Hi! I 've a code to read an excel file using JDBC-ODBC bridge. I can read the values, but any special characters is readed wrong, just symbols. The special characters are of spanish language. This is my code:
Locale currentLocale;
currentLocale = new Locale("es", "MX");
Locale.setDefault(currentLocale);
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
c = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ=comisionesperfiles.xls");
stmnt = c.createStatement();
String query = "Select * from [Hoja1$]" ;
ResultSet rs = stmnt.executeQuery( query );
while( rs.next() ){
String valor = rs.getString(2) ;
if(valor != null && !"null".equalsIgnoreCase(valor)){
if(!comisiones.contains(valor)){
System.out.println(valor);
comisiones.add( valor );
rs.close();
stmnt.close();As you can see, I've tried to set the locale, but it didn't work.
I'm using Excel 2003, Java Version 1.4.2_07 and Windows XP Professional (in latin american spanish).
Hope someone can help me!FYI: Apache's POI can read/write Excel files in Java:
http://jakarta.apache.org/poi/index.html -
Using JDBC to perform spatial queries using SDO operators
Hi,
I want to create a routine to perform the SDO_ANYINTERACT function based on a rectangle as in the following query:
select LINK_ID from SDO_LINK where
SDO_ANYINTERACT ( SDO_LINK.LINK, SDO_GEOMETRY(2003,8307,NULL,
SDO_ELEM_INFO_ARRAY(1,1003,3),
SDO_ORDINATE_ARRAY(-122.38845,37.78889,-122.38651,37.78923))) = 'TRUE'"
This query works fine when passed to the executeQuery method of a JDBC Statement. But when I tried to create a PreparedStatement and set the 4 parameters (lon1, lat1, lon2, lat2) that are passed to the SDO_ORDINATE_ARRAY function:
String sql = "select LINK_ID from SDO_LINK where " +
"SDO_ANYINTERACT ( SDO_LINK.LINK, SDO_GEOMETRY(2003,8307,NULL,SDO_ELEM_INFO_ARRAY(1,1003,3),SDO_ORDINATE_ARRAY(" +
"?,?,?,?" +
"))) = 'TRUE'";
I am getting an Oracle exception:
java.sql.SQLException: ORA-03115: unsupported network datatype or representation
I have tried setting the parameters using setString as well as setFloat methods but still get this error.
Does anyone know what I am dong wrong? Anyone have an example of calling SDO_ANYINTERACT or other SDO operators via JDBC?
Thanks
BWGetting the connection is straightforward:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
throw new SQLException (e.toString());
Connection conn = DriverManager.getConnection(connURL, userName, userPass);
I have validated that my query executes and returns results fine when I pass the entire query as a string to executeQuery:
String sql = "select LINK_ID from SDO_LINK where SDO_ANYINTERACT ( SDO_LINK.LINK, SDO_GEOMETRY(2003,8307,NULL,SDO_ELEM_INFO_ARRAY(1,1003,3),SDO_ORDINATE_ARRAY(-122.38845,37.78889,-122.38651,37.78923))) = 'TRUE'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
// Iterate through result set here
The issue is I am not sure how to pass the 2 (lon,lat) cooridnates fior the SDO_ORDINATE_ARRAY operation in a prepared statement . Perhaps I have to just construct a string?
For example, doing the following:
String sql = "select LINK_ID from SDO_LINK where " +
"SDO_ANYINTERACT ( SDO_LINK.LINK, SDO_GEOMETRY(2003,8307,NULL,SDO_ELEM_INFO_ARRAY(1,1003,3),SDO_ORDINATE_ARRAY(" +
"?,?,?,?" +
"))) = 'TRUE'";
if (conn == null)
openConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setFloat(1, Float.parseFloat(lon1));
pstmt.setFloat(2, Float.parseFloat(lat1));
pstmt.setFloat(3, Float.parseFloat(lon2));
pstmt.setFloat(4, Float.parseFloat(lat2));
Then calling:
ResultSet rs = pstmt.executeQuery(sql);
Which results in the exception.
Actually, I found the problem. I want to NOT pass the sql string to the executeQuery statement when using the PreparedStatement.
The following works:
ResultSet rs = pstmt.executeQuery();
Edited by: wisegb on May 21, 2009 5:39 AM
Maybe you are looking for
-
Please help
-
ITunes 7 and 7.01 screws with my computer
After installing iTunes 7 I just now realized it BOGS down my computer and even my windows load time on start up. For whatever reason, the crap it loads when windows is booting, it takes my wireless network card 2 extra minutes to initialize. Nuts to
-
Import DNG preference not working
I have set the import extension as dng to auto import as dng from a Canon 40D. Doesn't happen and after I import I have to convert the raw to dng. Is there anything I need to do in addition to setting the preference? Jay Gould
-
Hi , How do u calculate the US & india payroll taxes ? How do u calculate time recording for employees ? Edited by: Kaladhar Reddy on Mar 9, 2008 8:15 PM
-
Is Searching iCloud Calendar Possible?
I love how you can look at your iCloud calendars via a web browser in addition to your iOS devices (iPhone 5/ iPad / etc.)...but perhaps I am overlooking something in the interface...but I cannot seem to do a simple search of your calendar in ANY WAY