Problem in JDBC
Hiii all,
i want to make a page for username and password and i connected it with a database that contains the usernames and passwords
now i want to know how can i make a query (select password from table where username=the string that the user enter it) to match it with the password which i have in the database i write in the class:
static final String JDBC_DRIVER="sun.jdbc.odbc.JdbcOdbcDriver";
static final String DATABASE_URL="jdbc:odbc:Fees"
and in the try i write:
Class.forName(JDBC_DRIVER);
connection= DriverManager.getConnection(DATABASE_URL);
statement= connection.createStatement();
get=Integer.parseInt(textField1.getText());
ResultSet result=statement.executeQuery("SELECT Password FROM Fees WHERE Fees.StudentNo='"+get+"';");
but thats wrong, can anybody help me
PreparedStatement name= connection.prepareStatement("SELECT StudentName FROM Fees WHERE StudentNo=ID");That SQL statment will get all the rows from the Fees table where the column named StudentNo is equal to the column named ID; if those 2 columns don't exist, then you should get a SQLException, which you should by catching and printing because it will almost certainly give you a clue that your code is bad.
What I'm guessing you want is:
PreparedStatement name= connection.prepareStatement("SELECT StudentName FROM Fees WHERE StudentNo=?");
name.setString(1,ID);
ResultSet result=name.executeQuery();If the StudentNo column is a of a numeric type in the database, then the ID variable should be converted in your Java code (where you can more gracefully deal with conversion errors) to an appropriate numeric type, such as int, and you should call the appropriate set method for that numeric type, such as setInt().
By the way, notice how more readable the code is in my post, compared to yours; that's done by using the code button (or typing in the tags manually), and if you continue to post here, you should start to use it as a courtesy to the people you volunteer their time to answer your questions.
Similar Messages
-
I have a problem with JDBC Realm in Tomcat/Oracle/Win XP
I have a problem with JDBC Realm in Tomcat.
I have attached my server.xml file located in the
C:\Program Files\Apache Software Foundation\Tomcat 5.5\conf\server.xml
The Problem is that when I login I get the user name and password prompt but it does not resolve.
When I enter in the tomcat-users.xml password with memory realm uncommented it works fine.
C:\Program Files\Apache Software Foundation\Tomcat 5.5\conf\tomcat-users.xml
Is there a cache or something I need to reset for the JDBC Realm to work?
I have attached my tables and contents as well...
Did I miss something????
Thanks
Phil
server.xml
<Server port="8005" shutdown="SHUTDOWN">
<Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
<Listener className="org.apache.catalina.storeconfig.StoreConfigLifecycleListener"/>
<!-- Global JNDI resources -->
<GlobalNamingResources>
<!-- Test entry for demonstration purposes -->
<Environment name="simpleValue" type="java.lang.Integer" value="30"/>
</GlobalNamingResources>
<!-- Define the Tomcat Stand-Alone Service -->
<Service name="Catalina">
<!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
<Connector
port="8080" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" />
<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8009"
enableLookups="false" redirectPort="8443" protocol="AJP/1.3" />
<!-- Define the top level container in our container hierarchy -->
<Engine name="Catalina" defaultHost="localhost">
<!--
<Realm className="org.apache.catalina.realm.MemoryRealm" />
-->
<Realm className="org.apache.catalina.realm.JDBCRealm"
driverName="oracle.jdbc.driver.OracleDriver"
connectionURL="jdbc:oracle:thin:@localhost:1521:orcl"
connectionName="testName" connectionPassword="testPass"
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" appBase="webapps"
unpackWARs="true" autoDeploy="true"
xmlValidation="false" xmlNamespaceAware="false">
</Host>
</Engine>
</Service>
</Server>
Tables
create table users
user_name varchar(15) not null primary key,
user_pass varchar(15) not null
create table roles
role_name varchar(15) not null primary key
create table user_roles
user_name varchar(15) not null,
role_name varchar(15) not null,
primary key( user_name, role_name )
select * from users;
----------------------+
| user_name | user_pass |
----------------------+
| tomcat | tomcat |
| user1 | tomcat |
| user2 | tomcat |
| user3 | tomcat |
----------------------+
select * from roles;
| role_name |
| tomcat |
| role1 |
select * from user_roles;
-----------------------+
| role_name | user_name |
-----------------------+
| tomcat | user1 |
| role1 | user2 |
| tomcat | tomcat |
| role1 | tomcat |
-----------------------+Jan 2, 2008 11:49:35 AM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
Jan 2, 2008 11:49:35 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 734 ms
Jan 2, 2008 11:49:35 AM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Jan 2, 2008 11:49:35 AM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/5.5.9
Jan 2, 2008 11:49:35 AM org.apache.catalina.realm.JDBCRealm start
SEVERE: Exception opening database connection
java.sql.SQLException: oracle.jdbc.driver.OracleDriver
at org.apache.catalina.realm.JDBCRealm.open(JDBCRealm.java:684)
at org.apache.catalina.realm.JDBCRealm.start(JDBCRealm.java:758)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1004)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:442)
at org.apache.catalina.core.StandardService.start(StandardService.java:450)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:683)
at org.apache.catalina.startup.Catalina.start(Catalina.java:537)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:271)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:409)
Jan 2, 2008 11:49:35 AM org.apache.catalina.core.StandardHost start
INFO: XML validation disabled
Jan 2, 2008 11:49:36 AM org.apache.catalina.core.StandardContext resourcesStart -
Problem in JDBC Adapter Mapping
Hi all,
I am working on a scenario wherein i am trying to connect an ORACLE DB to SAP 4.7 system using XI 3.0 . I configured the JDBC Adapter and the JDBC adpter is picking up the message but i have a problem in JDBC adpter Mapping.
The error message is like this:
<!-- Request Message Mapping
-->
- <SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="">
<SAP:Category>Application</SAP:Category>
<SAP:Code area="MAPPING">EXCEPTION_DURING_EXECUTE</SAP:Code>
<SAP:P1>com/sap/xi/tf/_ORACLE_MSGMAP_</SAP:P1>
<SAP:P2>com.sap.aii.utilxi.misc.api.BaseRuntimeException</SAP:P2>
<SAP:P3>RuntimeException in Message-Mapping transformatio~</SAP:P3>
<SAP:P4 />
<SAP:AdditionalText />
<SAP:ApplicationFaultMessage namespace="" />
<SAP:Stack>During the application mapping com/sap/xi/tf/_ORACLE_MSGMAP_ a com.sap.aii.utilxi.misc.api.BaseRuntimeException was thrown: RuntimeException in Message-Mapping transformatio~</SAP:Stack>
<SAP:Retry>M</SAP:Retry>
</SAP:Error>
How to map the "Resultset" from the Adapter to a target message? Can anybody throw some light on how to get the message from the JDBC adpter and map it to some other message format...Any documents regarding this ?
Waitin for ur replies...
Bye,
Romit Shankar Arun.Hi,
Does your other SDN post "Inserting data through JDBC adapter" refer to the same problem?
I assume you use XMLSPY for creating XSDs.
I used the XSD posted by you in the other forum thread and tried to generate the XML structure and it does not seem to generate the XML structure in the format required by the JDBC adapter.
sample file generated from your XSD posted in the other forum thread:
<?xml version="1.0" encoding="UTF-8"?>
<resultset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="C:\Untitled1.xsd">
<row action="INSERT">
<CUSTOMER_NUMBER>String</CUSTOMER_NUMBER>
<COUNTRY_KEY>String</COUNTRY_KEY>
<FIRST_NAME>String</FIRST_NAME>
<LAST_NAME>String</LAST_NAME>
<AUTHORIZATION_GROUP>String</AUTHORIZATION_GROUP>
<INDUSTRY_KEY>String</INDUSTRY_KEY>
<ACCOUNT_GROUP>String</ACCOUNT_GROUP>
<INTIAL_CONTACT>String</INTIAL_CONTACT>
<COMPANY_CODE>String</COMPANY_CODE>
<CITY>String</CITY>
<CITY_CODE>String</CITY_CODE>
<COUNTRY_CODE>String</COUNTRY_CODE>
<DISTRICT>String</DISTRICT>
<FAX_NUMBER>String</FAX_NUMBER>
<HOUSE_NUMBER>String</HOUSE_NUMBER>
<POSTAL_CODE>String</POSTAL_CODE>
<REGION>String</REGION>
<TELEPHONE_NUMBER>String</TELEPHONE_NUMBER>
</row>
</resultset>
Compare the above to the template i have mentioned.
Hope this helps.
Regards,
Sridhar -
Problem in JDBC , when using LIKE operator. - VERY URGENT
Problem in JDBC , when using LIKE operator.
LINE 1 : String temp = "AA";
LINE 2 : String query = "select * from emp where EMPNAME like '*temp*' ";
LINE 3 : Staement st = con.createStaement();
LINE 4 : ResultSet rs = st.executeQuery(query);
'*' character is not getting evaluated. In MS ACCESS2000 only * is accepted instead of '%'. Moreover in MS ACCESS the like operator has to be used within double quotes as a String. whereas in other databases, it accepts single quotes as a String.
Ex:
In MS ACCESS
select * from emp where ename like "*aa*";
Other Databases
select * from emp where ename like '%aa%';
In my situation iam passing a Variable inside a like operator and '*' is used.
For the above Scenario, Please help me out.
If possible Kindly let me know the exact Syntax.
Please give me the answer as LINE1,LINE2,LINE3,LINE4,
I have verified in JDBC Spec also, it has been specified to use escape sequence.that too did not work.
Due to this, My project is in hold for about 4 days. I could not find a suitable solution.
Please help me out.I made a LIKE clause work with M$ Access, using PreparedStatement and the % wildcard:
escapeStr = "%";
String sql = "SELECT USERNAME, PASSWORD FROM USERS WHERE USERNAME LIKE ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, ("user" + escapeStr));
ResultSet resultSet = statement.executeQuery();
while (resultSet.next())
System.out.println("username: " + resultSet.getObject("USERNAME") + " password: " + resultSet.getObject("PASSWORD")); -
hello,
a very big problem.
I configured in my PI 7.1 installation a JDBC - PI - rfc interface.
When i active the jdbc comunication channel , all cpu saturated and j2ee crash.
I try to restart java stack but is not possible
I think the problem is on jdbc adapter but i cannot stop it if java part is down.
There are solution for stop or delete this comunication channell from abap stack?
does someone already had a similar problem that jdbc adapter generate a crash of system?
thanks>
Alessandro Pederiva wrote:
> ok thanks, we try
> which is the correct connection string for connection on SQL server??
> i used :
>
> driver: sun.jdbc.odbc.JdbcOdbcDriver
> connection : jdbc:odbc:Driver={SQL Server};Server=host;Database=dbname
Are you using a JDBC-ODBC bridge type driver, I am not sure if this is supported by JDBC adapter.....
If it is not try this,
Driver: com.microsoft.jdbc.sqlserver.SQLServerDriver
Connection: jdbc:microsoft:sqlserver://SQLHOSTNAME:PORT;DatabaseName=DBNAME;SelectMethod=cursor -
A very surprise problem about JDBC and connection pool
I occur a very problem about JDBC and connection pool on Weblogic Platform
8.1.
There is a table in Oracle
Table
Name: t1
id varchar2(5);
content clob;
id is primary key.
If I use a connection pool to connect to Oracle,like following program:
InitialContext ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup("cgOracleDataSource");
con = ds.getConnection();
then following program will throw a ClassCastException
String sql = "select content from t1 where id = ?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1,"001");
oracle.sql.CLOB clob = (oralce.sql.CLOB)rs.getClob("content") //this
statement will throw ClassCastException
but if I use JNDI to connect to Oracle,like following program, then those
program above is ok
private String dbdriver="oracle.jdbc.driver.OracleDriver";
private String dburl="jdbc:oracle:thin:@192.168.7.148:1521:ep";
private String username="ep";
private String password="epuser";
Class.forName(dbdriver);
conn = DriverManager.getConnection(dburl, username, password);
conn.setAutoCommit(false);
On the contrary, if I use JNDI to connect to Oracle, following program will
throw ClassCastException
weblogic.jdbc.vendor.oracle.OracleThinClob clob =
(weblogic.jdbc.vendor.oracle.OracleThinClob)rs.getClob("content");
but it is fine if I use connection pool to connect to Oracle.
I am confused this problem, who can tell me why?
DanielWhen you are getting connection using datasource lookup from weblogic
connection pool, this connection is internally wrapped and hence you have to
cast it to weblogic.jdbc.vendor.oracle.OracleThinClob which you do and so it
works.
But when you get connection by loading driver straight, you are getting naked
oracle connection. In this case when you cast it to oracle.sql.Clob it works,
as you have seen in your test case.
I hope this explains what is going on with your code.
Thanks,
Mitesh
Daniel wrote:
I occur a very problem about JDBC and connection pool on Weblogic Platform
8.1.
There is a table in Oracle
Table
Name: t1
id varchar2(5);
content clob;
id is primary key.
If I use a connection pool to connect to Oracle,like following program:
InitialContext ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup("cgOracleDataSource");
con = ds.getConnection();
then following program will throw a ClassCastException
String sql = "select content from t1 where id = ?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1,"001");
oracle.sql.CLOB clob = (oralce.sql.CLOB)rs.getClob("content") //this
statement will throw ClassCastException
but if I use JNDI to connect to Oracle,like following program, then those
program above is ok
private String dbdriver="oracle.jdbc.driver.OracleDriver";
private String dburl="jdbc:oracle:thin:@192.168.7.148:1521:ep";
private String username="ep";
private String password="epuser";
Class.forName(dbdriver);
conn = DriverManager.getConnection(dburl, username, password);
conn.setAutoCommit(false);
On the contrary, if I use JNDI to connect to Oracle, following program will
throw ClassCastException
weblogic.jdbc.vendor.oracle.OracleThinClob clob =
(weblogic.jdbc.vendor.oracle.OracleThinClob)rs.getClob("content");
but it is fine if I use connection pool to connect to Oracle.
I am confused this problem, who can tell me why?
Daniel -
I'm having problems registering jdbc drivers. I've been trying to register the microsoft Sql Server 2000 jdbc driver so that I can create a connection in my code rather than using entity beans. I've set the CLASSPATH variable to point to the driver's .jar files in the install directory with no success.
I've connected to the database using the driver via the IDE' s Runtime and it tests ok and allows me to create a database schema ok. (I had to copy the driver files to the sun/studio5u1_se/lib/ext dir to enable this) Is there a location I can unpack the drivers .jar files which will make the driver available?
I have also tried setting the CLASSPATH variable to point to the above mentioned directory..but that didn't work either. Can anyone help?
These are the exception messages that I get
java.lang.ClassNotFoundException: com.pointbase.jdbc.jdbcUniversalDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:199)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:187)
at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274)
at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:141)
at Portfolio.DriverTest.getConnection(DriverTest.java:43)
at Portfolio.DriverTest.main(DriverTest.java:102)
Error Trace in getConnection() : com.pointbase.jdbc.jdbcUniversalDriverIf u type in command line
java -classpath .;<directory containing the driver>
it executes your class file properly
note that <directory containing the driver> is the full path to your driver. I mean, the directory that contains your driver\drivername
eg:
java -classpath .;c:/driver/drivername
don�t forget to put the "dot" before semicolon. If u forget it, java won�t find your class file. your class file must be at the directory you�re executing the command
I need to configure my sun studo ent. to locate my jdbc driver for mySQL. I don�t know where this can be made. If any of you know. please report me -
Problem with JDBC and VARCHAR-Columns
Hi,
i have a problem handling VARCHAR-Columns via JDBC.
I.e. by using the JDBC-components of <SunONE Community Edition Update 1> any attempt to store any other then numeric values (like "0", "01", "999" etc.) in a column of type VARCHAR results in an error.
After entering the string "test" in a JTextArea or JTextField (which is linked by its document to the VARCHAR-column) i will receive:
"java.lang.NumberFormatException: For input string: "st"/For input string: "st". I also tried the javax.sql. rowSet methods like updateString() with the same result.
Are there any knwon issues corresponding to this behaviour?
<b>Configuration details:</b>
<i>JDBC-Driver:</i>
package com.sap.dbtech.jdbc, MaxDB JDBC Driver, MySQL MaxDB, 7.5.1 Build 000-000-002-750 on Java 1.4.2
<i>Database-version:</i>
7.5.00.16 on WindowsXP Pro SP1
<i>JRE:</i>
1.4.1_02
The <i>trace-file</i> only show this statements:
[email protected] (UPDATE NOTARZTEINSATZPROTOKOLL_1 SET NEUROLOGISCHER_ERSTBEFUND = ? WHERE NAP_ID = ? AND EP_ID = ? AND BEMERKUNG IS NULL AND SOZ_ID IS NULL AND PSYZ_ID IS NULL AND ERSTBEFUND_ZEITPUNKT IS NULL AND GCSAO_ID_EB IS NULL AND GCSBVR_ID_EB IS NULL AND GCSBMR_ID_ARMLINKS_EB IS NULL AND GCSBMR_ID_ARMRECHTS_EB IS NULL AND GCSBMR_ID_BEINLINKS_EB IS NULL AND GCSBMR_ID_BEINRECHTS_EB IS NULL AND BWSL_ID_EB IS NULL AND EXTB_ID_ARMLINKS_EB IS NULL AND EXTB_ID_ARMRECHTS_EB IS NULL AND EXTB_ID_BEINLINKS_EB IS NULL AND EXTB_ID_BEINRECHTS_EB IS NULL AND PUPW_ID_LINKS_EB IS NULL AND PUPW_ID_RECHTS_EB IS NULL AND EJN_ID_FEHLTLICHTR_LI_EB IS NULL AND EJN_ID_FEHLTLICHTR_RE_EB IS NULL AND EJN_ID_MENINGISMUS_EB IS NULL AND NEUROLOGISCHER_ERSTBEFUND IS NULL AND TEMPERATUR_EB IS NULL AND RR_SYSTOLISCH_EB IS NULL AND RR_DIASTOLISCH_EB IS NULL AND HERZFREQUENZ_EB IS NULL AND EJN_ID_HF_REGELM_EB IS NULL AND BLUTZUCKER_EB IS NULL AND ATEMFREQUENZ_EB IS NULL AND SPO2_EB IS NULL AND CO2_EB IS NULL AND SCHM_ID_EB IS NULL AND ERH_ID_COR_EB IS NULL AND EELS_ID_COR_EB IS NULL AND EJN_ID_EKG_EMENTKOPPEL_EB IS NULL AND EERBST_ID_COR_EB IS NULL AND EHA_ID_COR_EB IS NULL AND ESVES_ID_COR_EB IS NULL AND EVES_ID_COR_EB IS NULL AND EKG_BEMERKUNG_EB IS NULL AND ATRH_ID_EB IS NULL AND EJN_ID_ZYANOSE_EB IS NULL AND EJN_ID_SPASTIK_EB IS NULL AND EJN_ID_RASSELGER_EB IS NULL AND EJN_ID_STRIDOR_EB IS NULL AND EJN_ID_VERLEGATEMW_EB IS NULL AND BEAM_ID_UEBERNAHME IS NULL AND ATMUNG_FREITEXT_EB IS NULL AND VERLM_ID IS NULL AND SCHWV_ID_SCHAEDELHIRN IS NULL AND SCHWV_ID_GESICHT IS NULL AND SCHWV_ID_HWS IS NULL AND SCHWV_ID_THORAX IS NULL AND SCHWV_ID_ABDOMEN IS NULL AND SCHWV_ID_BWSLWS IS NULL AND SCHWV_ID_BECKEN IS NULL AND SCHWV_ID_OEXTREMITAET IS NULL AND SCHWV_ID_UEXTREMITAET IS NULL AND SCHWV_ID_WEICHTEILE IS NULL AND VBRT_ID IS NULL AND TRT_ID IS NULL AND UHG_ID IS NULL AND SICHTK_ID IS NULL AND UNFALLZEITPUNKT IS NULL AND SAPS_2 IS NULL AND TISS_28 IS NULL AND NACA_ID IS NULL AND ZBV IS NULL )
=> com.sap.dbtech.jdbc.CallableStatementSapDB@11daf60
<at this position the trace-file ends?!; "NEUROLOGISCHER_ERSTBEFUND ist defined as
"NEUROLOGISCHER_ERSTBEFUND" Varchar (1000) ASCII; i also encountered this problem while handling shorter VARCHAR-columns with JComboBox-components...>
Any information would be very helpfully!!!
Greetings,
Arnd
Message was edited by: Arnd Benninghoff
Message was edited by: Arnd BenninghoffHi Arnd,
if I understand right you are trying to insert/update value into a Varchar(1000) column. And if you set a non numeric value you get an exception "java.lang.NumberFormatException", Right?
Of course this should work with MaxDB. The exception you get doesn't come from MaxDB's JDBC driver. The driver will only throw exceptions that are derived from java.sql.Exception.
So, I guess the error comes from a layer above the JDBC layer, possibly from the JDBC-components of <SunONE Community Edition Update 1>. This would also explain why you don't see any exception in the JDBC trace.
Did you have defined any constraints for the input field (JTextArea or JTextField)?
Hope that helps.
regards,
Marco -
WebLogic 10.3.2.0 (11gR1) on Solaris 10 problems with jdbc
I have Solaris 10 10/09 running on a SPARC machine.
I install WebLogic 11gR1, use development mode (using the SUN 1.6 jvm) and create a JDBC connection to DB2 on another machine using Oracle's XA DB2 driver. The connection test is successful. A restart of WebLogic returns everything is good. I change the connection pool max capacity to 50 (up from the default of 15) in the web interface and save the settings, everything is fine. Then I shutdown WebLogic using the appropriate command and re-start it... only to find that the jdbc connection has failed with the following error:
<Feb 22, 2010 11:02:31 AM EST> <Error> <Deployer> <BEA-149205> <Failed to initialize the application 'jdbc/DB2DataSource' due to error weblogic.application.ModuleException: .
weblogic.application.ModuleException:
at weblogic.jdbc.module.JDBCModule.prepare(JDBCModule.java:290)
at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:199)
at weblogic.application.internal.flow.DeploymentCallbackFlow$1.next(DeploymentCallbackFlow.java:391)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:83)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:59)
Truncated. see log file for complete stacktrace
Caused By: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_DEVICE_ERROR
at sun.security.pkcs11.wrapper.PKCS11.C_Verify(Native Method)
at sun.security.pkcs11.P11Signature.engineVerify(P11Signature.java:529)
at java.security.Signature$Delegate.engineVerify(Signature.java:1140)
at java.security.Signature.verify(Signature.java:592)
at sun.security.x509.X509CertImpl.verify(X509CertImpl.java:441)
Truncated. see log file for complete stacktrace
Nothing else is changed or deployed in WebLogic.
Switching back to a thread pool max of 15 doesn't work, and throws this error:
<Feb 22, 2010 11:09:41 AM EST> <Warning> <Deployer> <BEA-149004> <Failures were detected while initiating redeploy task for application 'jdbc/DB2DataSource'.>
<Feb 22, 2010 11:09:41 AM EST> <Warning> <Deployer> <BEA-149078> <Stack trace for message 149004
weblogic.application.ModuleException:
at weblogic.jdbc.module.JDBCModule.prepare(JDBCModule.java:290)
at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:199)
at weblogic.application.internal.flow.DeploymentCallbackFlow$1.next(DeploymentCallbackFlow.java:391)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:83)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:59)
Truncated. see log file for complete stacktrace
Caused By: java.lang.NoClassDefFoundError: Could not initialize class javax.crypto.SunJCE_b
at javax.crypto.SecretKeyFactory.a(DashoA13*..)
at javax.crypto.SecretKeyFactory.<init>(DashoA13*..)
at javax.crypto.SecretKeyFactory.getInstance(DashoA13*..)
at weblogic.jdbc.db2base.PropertyEncrypter.<init>(Unknown Source)
at weblogic.jdbc.db2base.BaseLicenseUtility.readBulkLoadRowLimit(Unknown Source)
Truncated. see log file for complete stacktrace
<Feb 22, 2010 11:09:42 AM EST> <Error> <Console> <BEA-240003> <Console encountered the following error weblogic.application.ModuleException:
at weblogic.jdbc.module.JDBCModule.prepare(JDBCModule.java:290)
at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:199)
at weblogic.application.internal.flow.DeploymentCallbackFlow$1.next(DeploymentCallbackFlow.java:391)
Modifying the connection in the xml to lower the max pool size back to the default value of 15 doesn't net any progress.
Removing and re-creating the connection doesn't fix the problem. Creating a new WebLogic domain doesn't fix the problem. The only thing that fixes the problem (allows the jdbc connection to be re-created and run successfully) is to blow away the entire WebLogic install, reinstall and re-create the domain. Occasionally even this doesn't help.
This is repeatable like clockwork.
Moving the pool max up to 30 didn't throw the error, but moving to 50 did.
Edited by: second infinity on Feb 22, 2010 2:24 PMHi. I've never seen anything like this, and it seems to be something which
the JDBC module is going to be an innocent victim of, rather than a
contributor to... Your best course is to open an official support case.
Joe -
$200 reward to solve problem with JDBC and CLOB.getCharacterOutputStream
I'm trying to update CLOB with the getCharacterOutputStream as suggested in the example code. It works with US7ASCII DB instance but not instances in UTF8.
I've been browsing through all the Oracle doc's and found some rather confusing statements:
In the page at http://oradoc.photo.net/ora816/java.816/a81354/oralob2.htm#1043220
it says: [When writing to or reading from a CLOB, the JDBC drivers perform all character set conversions for you.]
also: [The oracle.sql.CLOB class supports all the character sets that the Oracle data server supports for CLOB types.]
So far so good.
In the page at http://oradoc.photo.net/ora816/java.816/a81354/oraint3.htm#1012518
it says [The oracle.sql package supports these datatypes in several ways: CLOBs point to large fixed-width character data items (that is, characters that require a fixed number of bytes per character) and are supported by the oracle.sql.CLOB class.]
Ooh no! Is this for real? UTF8 is variable width and does this mean it is not supported?
Any way to get around this?
In the page at http://oradoc.photo.net/ora816/java.816/a81358/03_pub2.htm#36009
says [6.The mappings to oracle.sql classes are optimal because they preserve data formats and require no character-set conversions (apart from the usual network conversions). Those classes are especially useful in applications that "shovel" data between SQL and Java.]
"No character set conversion"? Very confusing!
I've been hammering on this CLOB/JDBC/UTF8 problem for more than a week now and I really appreciate some solutions, workarounds, or whatever help I can get. I'm running java stored procedure in 8.1.6 on Linux RH6.2.
For your trouble, I'd pay $200 for the first guy who come up with a verifiable solution.This is just findings based upon your comments:
Please refer to document Oracle8i National Language Support Guide
Release 2 (8.1.6) from Oracle Documentation Library, Release 8.1.7
Chapter 6 Java,
There its clearly mention that:
"Oracle JDBC drivers provide globalization support by allowing users to retrieve data from or insert data into a database in any character set that Oracle supports. Because Java strings are UCS2 encoded (16-bit Unicode) for JDBC programs, the target character set on the client is always UCS2. Character set conversion is required to convert data from the database character set (Db Charset) to UCS2. This applies to CHAR, LONG, CLOB, and VARCHAR2 data types; RAW data is not converted. "
Also..please refer this...
"oracle.sql.CLOB's method getCharacterStream() returns the contents of a CLOB as a Unicode stream."
"The techniques that Oracle's drivers use to perform character set conversion for Java applications depend on the character set the database uses. The simplest case is where the database uses a US7ASCII or WE8ISO8859P1 character set. In this case, the driver converts the data directly from the database character set to UCS2,which is used in Java applications. "
"If you are working with databases that employ a non-US7ASCII or non-WE8ISO8859P1 character set (for example, Japanese or Korean), then the driver converts the data, first to UTF8, then to UCS2. "
In my case the characte-set of the database is WE8ISO8859P1 and for security reason i can't change the character set but my feeling is that if you are updating the CLob from the java client you are forming a reference of a clob in the client which is UCS2 at the Java side. Now when you are populating the clob through java.io.Writer and call the procedure to pass the reference of the clob to the procedure then I believe the JDBC will convert the UCS2 datatype of Clob to UTF8 in the database.
You can try out the code snippet:
package ServletGDC;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import oracle.sql.*;
import java.sql.*;
import oracle.jdbc.driver.*;
import ClassesGDC.*;
public class testUpload extends HttpServlet {
private String m_strMessage="";//It stores the message to be uploaded along with the Document
Connection conn=null;
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String strContent="";
//res.setContentType("application/msword");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
try {
CallableStatement cmt=null;
OutputStream output=null;
ByteArrayOutputStream byteoutput=null;
String strDocString="";
oracle.sql.CLOB tempClob = null;
String strPassedFileName=""; // the file name passed in the request object
String strStdFilename="";//the file name to be given to the best practice
String strSaveDirectory=""; //the directory in which the bp is to be saved
String strParamName="";//name of parameters
String strParamValue="";//value of parameters
int intTempVariable=0; // temporaty variable
long lngSizeOfFileUploaded=0;//stores the size of the file which had been uploaded in the file system
File filePathOfFileUploaded=null;//stores the path of the file uploaded to the file system
String strQuery="";
//ST------------checks if the user has logged in or not-----------------------
HttpSession session=req.getSession(true);
if(req.getContentLength()>20*1024*1024)
throw new skip("The size of the posted content is more than 10 MB . If you have a best practice whose size is more than 1 MB please mail it to Us.");
byteoutput = new ByteArrayOutputStream();
MultipartParser mp = new MultipartParser(req, 20*1024*1024); // 10MB is the limit of the file to be uploaded
Part part;//Its an abstact part which helps in retrieving information about the file and the parameters
while ((part = mp.readNextPart()) != null) {//Reads the next part
strParamName = part.getName();
// the following if is executed if the part is for a parameter rather than a file
if (part.isParam()) {
}else if (part.isFile()) {
// it's a file part
m_strMessage="inside file part";
FilePart filePart = (FilePart) part;
strPassedFileName = filePart.getFileName();
strContent= filePart.getContentType();
out.println("<BR><font color=red>strPassedFileName is "+strPassedFileName+"</font>");
if(strPassedFileName != null || !(strPassedFileName.trim().equals("")) ) {
// the part actually contained a file
out.println("<BR><font color=red> before forming long</font>");
//lngSizeOfFileUploaded = filePart.writeTo(filePathOfFileUploaded); //the statement upload the bestpractice in the
lngSizeOfFileUploaded = filePart.writeTo(byteoutput); //specified file path filePathOfFileUploaded.
out.println("<BR><font color=red> after file is written into the outputstream</font>");
else {
throw new skip("The file name is null or it is empty space. Files in such Format are not accepted");
}//end of else if
}//end of while loop
if( lngSizeOfFileUploaded==0) {// the size of the file uploaded is zero then the file supplied was not proper and hence exception is to be thrown
//if(filePathOfFileUploaded.exists())
// filePathOfFileUploaded.delete();
throw new skip("The File could not be uploaded,Possible reasons may be that the file is sent null or the file is corrupted");
//END---------------the file is uploaded in the proper directory--------------------
//res.setContentType(strContent);
out.println("<BR><font color=red>long value is : "+lngSizeOfFileUploaded+" and content is "+strContent+"</font>");
String strbyte= byteoutput.toString();
byteoutput.flush();
Class.forName("oracle.jdbc.driver.OracleDriver");
// Establish network connection to database
conn = DriverManager.getConnection("jdbc:oracle:thin:@pc-p32670:1521:GDCDBI","gdc_user","myuser");
//if(conn!=null)
out.println("<BR><font color=red>Connection formed"+conn);
//els
//out.println("<BR><font color=red>long value is : "+strbyte+"</font>");
try{
tempClob = oracle.sql.CLOB.createTemporary(conn,true, oracle.sql.CLOB.DURATION_SESSION);
out.println("<BR><font color=red>tempClob : "+tempClob);
tempClob.open( oracle.sql.CLOB.MODE_READWRITE);
java.io.Writer tempClobWriter = tempClob.getCharacterOutputStream();
// writing the string formed from the multipart file to the clob
tempClobWriter.write(strbyte);
if(tempClob!=null){}
out.println("<BR><font color=red>CLOB value is : "+tempClob+"</font>");
strQuery="{call INSERT_CLOB(?,?)}";
cmt=conn.prepareCall(strQuery);
cmt.setString(1,strPassedFileName);
cmt.setClob(2,tempClob);
cmt.registerOutParameter(2,java.sql.Types.CLOB);
cmt.execute();
tempClobWriter.flush();
tempClobWriter.close();
tempClob.freeTemporary();
//res.setContentType(strContent);
//strDocString.toString();
out.println("<BR><font color=red>bob is "+strbyte+"</font>");
tempClob.close();
}catch(Exception e){
tempClob.close();
out.println("<font color=blue> Error is :"+e.getMessage()+"</font>");
//e.printStackTrace(out);
cmt.close();
//out.println("<BR><font color=red><h2><b>SUCCESS</h2></font>");
//res.sendRedirect("../test/showfile.jsp?contentype="+strContent.trim()+"");
}catch(Exception e){
java.util.Date d = new java.util.Date();
String s =d.toString();
out.println("<font color=blue> Error is :"+e.getMessage()+"</font>");
//e.printStackTrace(out);
}finally{
try{
if(conn!=null)
conn.close();
}catch(Exception e){
out.println("<font color=blue> Error is :"+e.getMessage()+"</font>");
}// end of finally
} //end of doPost
} //end of class
in the Procedure you will be inserting/updating the clob in a table with the reference clob in the out parameter of the procedure
Thanks. -
I don't know where the problem originate, the only thing in my memory is that the program worked very well on my PC yesterday, but today, without even slightest change, it doesn't work anymore. As to debug it, I simplified the codes to the least, but it still refuse to work. I was beaten down by this problem totally, and cannot make out any solution for it, so, I come here, hoping to find a warrior to kill this damned bug for me.
My program is a Servlet, but for the purpose of debugging, I have recode it to an Application/Servlet. When run as a application, I can get the result expected, but as a Servlet, :-(, maybe you should see it by yourself. My server software is Tomcat 4.1.15, and the JDK version is 1.4.0. To excute this program, you should add Data Source "Test" to ODBC.
///////////////////////code begins/////////////////////////
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class Ex extends HttpServlet
int ErrorType = 0;
String err = new String("");
public static void main(String args[]) throws Exception{
Ex cEx = new Ex();
cEx.init();
System.out.println(cEx.ErrorType);
public void init() {
String url = "jdbc:odbc:Test";
ErrorType = 3; //passed
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
ErrorType = 1; //trapped in Class.forName
try{
Connection c = DriverManager.getConnection(url);
} catch (SQLException e) {
e.printStackTrace();
ErrorType = 2; //trapped in DriverManager.getConnection
err = e.getMessage();
public void service(HttpServletRequest req, HttpServletResponse res)
throws IOException {
res.setContentType("text/html; charset=GB2312");
PrintWriter out = res.getWriter();
out.println("Success " + "<p>" + ErrorType + "<p>" +err);
out.close();
//////////////////////////code ends///////////////////////////////
The result from the Servlet tell me that the problem occurred within the connection process, I don't know who should be responsible to this - Tomcat or JDBC?If you could print the exception that you got then that would help :) In the mean time, I could make a guess. It is unlikely that your application server (in this case, Tomcat) is blocking connections from your servlet. So the problem is either with JDBC directly or with the underlying datasource. It seems unlikely that it is JDBC given that you have stated that the code has not changed and it works in application form.
My guess would be that you are coming up against some sort of security constraint (eg: your DBMS is letting you log in from one IP but not another?, your Java plug-in security policy is disallowing the connection?). It's hard to say.
But if it works as an application but not via a servlet then you could try putting this in your java.policy file, which is located in the directory where your plug-ins are installed (eg: "C:\Program Files\Java\<version>\lib\security\") on Windows systems;
permission java.net.SocketPermission "bend xp:1099", "listen,connect,accept";
Try that, see if it works :)
Ben -
JDeveloper 10.1.3.2.0 and database 11g, problem in JDBC ?
We developed our j2ee application (using hibernate) for some time. Now we came to newer Oracle database 11g and have problem - endless waiting for fetched data. I think, that problem is in JDBC version.
Adding new JDBC into project as new library and placing it 'before' the old one doesn't help. Btw. hibernate gets connection from applicationContext_dataSource.xml file and is defined for example like this
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@host:port:SID"/>
<property name="username" value="name"/>
<property name="password" value="password"/>
</bean>
It has nothing to do with defined conections.
My question is this:
- Can I upgrade JDBC in our 10.1.3.2.0 JDeveloper to new version or latest version of JDeveloper is needed ?
Thanks.
Message was edited by:
jnejedlyThe OC4J server embedded in JDeveloper 11g does not support JDBC 4.0.
Java applications using the JDBC 4.0 driver may be developed in JDeveloper 11g. -
Problem creating JDBC dataview to oracle on Windows
Hi,
I'm trying to configure a JDBC dataview to an Oracle 10g database on DSEE 6.3.1 running Windows 2008
Here are the command I used:
dpconf create-jdbc-data-source -b MYDBSID -B jdbc:oracle:thin://dbhost:1510: \
-J file://e:\dsee\ojdbc14.jar \
-S oracle.jdbc.driver.OracleDriver mydb
echo "password" > e:\dsee\instances\mydb.pwd
dpconf set-jdbc-data-source-prop mydb db-user:myuser \
db-pwd-file:e:\dsee\instances\mydb.pwd \
is-enabled:true is-read-only:true \
dpconf create-jdbc-data-source-pool mypool
dpconf attach-jdbc-data-source mypool mydbAnd when trying to create the view with this command:
dpconf create-jdbc-data-view myview mypool o=example.comHere is what I get:
[LDAP: error code 1 - Unable to apply configuration changes: Exception catched while initializing
JDBC driver oracle.jdbc.driver.OracleDriver in configuration entry cn=mydb,cn=data sources,cn=config --
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver. Check that [Ljava.lang.String;@100
bac2 is a valid URL to a jar file containing class oracle.jdbc.driver.OracleDriver]".
{code}
I guess that it doesn't find the jdbc driver for Oracle but the file is there in e:\dsee\ojdbc14.jar
I tried to copy it to e:\dsee\dps6\lib but it doesn't work better.
Any idea ?
Frederic.I found the solution by adapting the path to the jdbc jar file:
dpconf set-jdbc-data-source-prop ehldb driver-url:file:///e:/dsee/ojdbc14.jarAdding a third slash after file: and using backslashes instead of slashes solved my problem.
Frederic. -
Problem in jdbc-tomcat-mysql connection
hi everybody
i m in serious problem since last 15-20 days. i m trying hard to make the connection jdbc-mysql using tomcat with the help of a jsp test page but every time i am facing almost the similar probems listed below in detail:
to make sure that the jdrivers's .jar (mysql-connector-java-3.1.7-bin.jar) available for such connections working fine i have tried the above said connection without using tomcat....which is working fine...for this i have created a dummy database with a dummy table ..and written some queries in the .java file of my code which upon running inserts the specified values in the defined(dummy) database.
this is the confirmation that the classpath etc..are ok in regard to the mysql-connector-java-3.1.7-bin.jar
now i have placed a copy of this .jar file in to the commons/lib directory of the tomcat web server(which is suppossed to be the place for such external jars)
after doing so i have followed 2 methods :
method 1st:........
i have made aone more jar file from the following .java file....
import javax.naming.*;
import javax.sql.*;
import java.sql.*;
public class TestSQLLoad
String user = "Not Connected";
String pwd = "no pwd";
int id = -1;
public void init() {
try{
Context ctx = new InitialContext();
if(ctx == null ) {
throw new Exception("Boom - No Context");
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/TestDB");
if (ds != null) {
Connection conn = ds.getConnection();
if(conn != null) {
user = "Got Connection "+conn.toString();
Statement stmt = conn.createStatement();
String q = "select name, password, id from user";
ResultSet rst = stmt.executeQuery(q);
if(rst.next()) {
user=rst.getString(1);
pwd=rst.getString(2);
id = rst.getInt(3);
conn.close();
}catch(Exception e) {
e.printStackTrace();
public String getUser() {
return user;
public String getPassword() {
return pwd;
public int getID()
return id;
after compiling it at the cmd prompt i made a .jar file from the .class of it and named it MySQLLoad.jar...then i placed it also in to the commons/lib directory where the mysql-connector-java-3.1.7-bin.jar was already placed.
then i have changed the server.xml and web.xml files from the conf directory of the tomcat as given here:
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">
<!-- Comment these entries out to disable JMX MBeans support used for the
administration web application -->
<Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
<!-- 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"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
</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 HTTP/1.1 Connector on port 8080 -->
<Connector
port="80" maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
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 HTTP/1.1 Connector on port 8443 -->
<!--
<Connector port="8443"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" disableUploadTimeout="true"
acceptCount="100" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
-->
<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8009"
enableLookups="false" redirectPort="8443" 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" 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 AJP ie :
<Engine name="Standalone" defaultHost="localhost" jvmRoute="jvm1">
-->
<!-- Define the top level container in our container hierarchy -->
<Engine name="Catalina" defaultHost="localhost">
<!-- 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"/>
-->
<!-- 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"
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"
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"
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"
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" 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
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: (only for SimpleTcpReplicationManager)
<%
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"
notifyListenersOnReplication="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"
ackTimeout="15000"/>
<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" />
-->
<!-- 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"/>
-->
<!-- 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.
This access log implementation is optimized for maximum performance,
but is hardcoded to support only the "common" and "combined" patterns.
-->
<!--
<Valve className="org.apache.catalina.valves.FastCommonAccessLogValve"
directory="logs" prefix="localhost_access_log." suffix=".txt"
pattern="common" resolveHosts="false"/>
-->
<Context path="/testdb" docBase="TOMCAT_HOME/webapps/tomcat-docs/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>root</value>
</parameter>
<parameter>
<name>password</name>
<value>mysql</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>
and the other xml file i.e
web.xml is here:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<!-- ======================== Introduction ============================== -->
<!-- This document defines default values for all web applications -->
<!-- loaded into this instance of Tomcat. As each application is -->
<!-- deployed, this file is processed, followed by the -->
<!-- "/WEB-INF/web.xml" deployment descriptor from your own -->
<!-- applications. -->
<!-- -->
<!-- WARNING: Do not configure application-specific resources here! -->
<!-- They should go in the "/WEB-INF/web.xml" file in your application. -->
<!-- ================== Built In Servlet Definitions ==================== -->
<!-- The default servlet for all web applications, that serves static -->
<!-- resources. It processes all requests that are not mapped to other -->
<!-- servlets with servlet mappings (defined either here or in your own -->
<!-- web.xml file. This servlet supports the following initialization -->
<!-- parameters (default values are in square brackets): -->
<!-- -->
<!-- debug Debugging detail level for messages logged -->
<!-- by this servlet. [0] -->
<!-- -->
<!-- input Input buffer size (in bytes) when reading -->
<!-- resources to be served. [2048] -->
<!-- -->
<!-- listings Should directory listings be produced if there -->
<!-- is no welcome file in this directory? [true] -->
<!-- -->
<!-- output Output buffer size (in bytes) when writing -->
<!-- resources to be served. [2048] -->
<!-- -->
<!-- readonly Is this context "read only", so HTTP -->
<!-- commands like PUT and DELETE are -->
<!-- rejected? [true] -->
<!-- -->
<!-- readmeFile File name to display with the directory -->
<!-- contents. [null] -->
<!-- -->
<!-- For directory listing customization. Checks localXsltFile, then -->
<!-- globalXsltFile, then defaults to original behavior. -->
<!-- -->
<!-- localXsltFile Make directory listings an XML doc and -->
<!-- pass the result to this style sheet residing -->
<!-- in that directory. This overrides -->
<!-- globalXsltFile[null] -->
<!-- -->
<!-- globalXsltFile Site wide configuration version of -->
<!-- localXsltFile This argument is expected -->
<!-- to be a physical file. [null] -->
<!-- -->
<!-- -->
<servlet>
<servlet-name>default</servlet-name>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- The "invoker" servlet, which executes anonymous servlet classes -->
<!-- that have not been defined in a web.xml file. Traditionally, this -->
<!-- servlet is mapped to the URL pattern "/servlet/*", but you can map -->
<!-- it to other patterns as well. The extra path info portion of such a -->
<!-- request must be the fully qualified class name of a Java class that -->
<!-- implements Servlet (or extends HttpServlet), or the servlet name -->
<!-- of an existing servlet definition. This servlet supports the -->
<!-- following initialization parameters (default values are in square -->
<!-- brackets): -->
<!-- -->
<!-- debug Debugging detail level for messages logged -->
<!-- by this servlet. [0] -->
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>
org.apache.catalina.servlets.InvokerServlet
</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- The JSP page compiler and execution servlet, which is the mechanism -->
<!-- used by Tomcat to support JSP pages. Traditionally, this servlet -->
<!-- is mapped to the URL pattern "*.jsp". This servlet supports the -->
<!-- following initialization parameters (default values are in square -->
<!-- brackets): -->
<!-- -->
<!-- checkInterval If development is false and checkInterval is -->
<!-- greater than zero, background compilations are -->
<!-- enabled. checkInterval is the time in seconds -->
<!-- between checks to see if a JSP page needs to -->
<!--Look at the URl below:
How to connect to Microsoft SQL server with Type 4 JDBC driver
http://www.java-tips.org/content/view/615/29/ -
Ms Access problems with Jdbc Odbc!!!
Hi again people,
Im creating a GUI swing project connecting a database (MsAccess) to a dialog using the bridge driver,
The GUI is coming up but im getting runtime errors and the data does not go to the fields, the dialog and connection are in two files:
import java.awt.*;
import java.awt.event.*;
import java.sql.*; //SQL package for the statements
import javax.swing.*;
class DatabaseMan
public ResultSet m_resultSet; //recordset resulting from SQL query
public ResultSetMetaData m_rsmd; //used to get general info about the columns
private int m_nNumberOfFields; //number of fields in a recordset
private Connection conn;
private Statement stmt;
public DatabaseMan(String strSQLQuery)
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
try //establish connection to the database
//try to get connection to the database
conn = DriverManager.getConnection("jdbc:odbc:db1");
//this is not where we update the database so we make it read only
stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
m_resultSet = stmt.executeQuery(strSQLQuery);
catch(SQLException exSQL)
System.err.println("\n\n\t\t ***SQLException has" +
"been caught ***\n\n");
while ( exSQL != null)
System.err.println("\nSQLState : " + exSQL.getSQLState() );
System.err.println("\nMessage : " + exSQL.getMessage() );
System.err.println("\nVendor code : "+ exSQL.getErrorCode() );
System.err.println("\n");
exSQL = exSQL.getNextException();
catch( ClassNotFoundException e)
System.err.print("\n\n\tClassNotFoundException has"
+" been caught");
System.err.println( e.getMessage());
catch( java.lang.Exception ex )
ex.printStackTrace();
public void CloseConnection() //close connection to database
try
conn.close();
stmt.close();
m_resultSet.close(); //release the resources
catch (SQLException exSQL )
System.out.println("SQL Exception: " + exSQL.getMessage());
exSQL.printStackTrace(System.out);
public int getNoFields()
return m_nNumberOfFields;
} //end of DatabaseMan.java
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import DatabaseMan;
import javax.swing.*;
class DBviewer extends JDialog implements ActionListener
//JButtons to create toolbar
private JButton m_buttonFirst;
private JButton m_buttonNext;
private JButton m_buttonPrevious;
private JButton m_buttonLast;
private JButton m_buttonClose;
private JButton m_mainbuttonClose;
//textfields to transfer the data from database
private JTextField m_name;
private JTextField m_age;
private JTextField m_weight;
private JTextField m_professionalism;
private JTextField m_speed;
private JTextField m_acceleration;
private JTextField m_jump;
private JTextField m_stamina;
private JTextField m_bravery;
private JTextField m_fitness;
private JTextField m_experience;
//labels to identify the textfields
private JLabel m_labelname;
private JLabel m_labelage;
private JLabel m_labelweight;
private JLabel m_labelspeed;
private JLabel m_labelacceleration;
private JLabel m_labelprofessionalism;
private JLabel m_labeljump;
private JLabel m_labelstamina;
private JLabel m_labelbravery;
private JLabel m_labelfitness;
private JLabel m_labelexperience;
DatabaseMan m_DatabaseMan;
private String strSQLQuery1;
private String type1 = new String("");
public DBviewer(Frame parent, String caption, boolean bModal, String type)
super(parent,caption,true);
setSize(600,400);
setLocation( new Point(150 , 150 )); //position it pops up on screen.
setResizable(false);
strSQLQuery1 = new String("");
type1 = type;
//SQL query to show the horse database
if(type =="Horse")
strSQLQuery1 ="SELECT *" +
"FROM HORSE";
buildHorseGUI();
if(type =="Jockey")
strSQLQuery1 ="SELECT *" +
"FROM JOCKEY"+
" ORDER BY NAME";
buildJockeyGUI();
if(type =="Course")
strSQLQuery1 ="SELECT *" +
"FROM RACECOURSE"+
" ORDER BY NAME";
buildCourseGUI();
m_DatabaseMan = new DatabaseMan(strSQLQuery1);
/*try
{//reset values with default move up to top later
if(m_DatabaseMan.m_resultSet.first())
transferData(type1);
catch( SQLException exSQL)
System.out.println("SQL Exception: " + exSQL.getMessage());
exSQL.printStackTrace(System.out);
public void buildHorseGUI() //construct the horse GUI
buildDefaultGUI(); //build default buttons and toolbar
m_labelname = new JLabel(" Horse Name:",JLabel.CENTER);
m_labelname.setBackground(Color.blue);
m_labelname.setForeground(Color.white);
m_labelage = new JLabel("Age: ",JLabel.CENTER);
m_labelage.setBackground(Color.blue);
m_labelage.setForeground(Color.white);
m_labelweight = new JLabel("Weight(p): ",JLabel.CENTER);
m_labelweight.setBackground(Color.blue);
m_labelweight.setForeground(Color.white);
m_labelspeed = new JLabel("Speed:",JLabel.CENTER);
m_labelspeed.setBackground(Color.blue);
m_labelspeed.setForeground(Color.white);
m_labelacceleration = new JLabel("Acceleration:",JLabel.CENTER);
m_labelacceleration.setBackground(Color.blue);
m_labelacceleration.setForeground(Color.white);
m_labelprofessionalism = new JLabel("Professionalism:",JLabel.CENTER);
m_labelprofessionalism.setBackground(Color.blue);
m_labelprofessionalism.setForeground(Color.white);
m_labeljump = new JLabel("Jump:",JLabel.CENTER);
m_labeljump.setBackground(Color.blue);
m_labeljump.setForeground(Color.white);
m_labelstamina = new JLabel("Stamina:",JLabel.CENTER);
m_labelstamina.setBackground(Color.blue);
m_labelstamina.setForeground(Color.white);
m_labelbravery = new JLabel("Bravery:",JLabel.CENTER);
m_labelbravery.setBackground(Color.blue);
m_labelbravery.setForeground(Color.white);
m_labelfitness = new JLabel("Fitness:",JLabel.CENTER);
m_labelfitness.setBackground(Color.blue);
m_labelfitness.setForeground(Color.white);
m_labelexperience = new JLabel("Experience",JLabel.CENTER);
m_labelexperience.setBackground(Color.blue);
m_labelexperience.setForeground(Color.white);
//creation of textfields to hold the data
//making them non-editable and b/ground of black with white text
m_name = new JTextField(20);
m_name.setEditable(false);
m_name.setBackground(Color.black);
m_name.setForeground(Color.white);
m_age = new JTextField(2);
m_age.setEditable(false);
m_age.setBackground(Color.black);
m_age.setForeground(Color.white);
m_weight = new JTextField(3);
m_weight.setEditable(false);
m_weight.setBackground(Color.black);
m_weight.setForeground(Color.white);
m_speed = new JTextField(2);
m_speed.setEditable(false);
m_speed.setBackground(Color.black);
m_speed.setForeground(Color.white);
m_acceleration = new JTextField(2);
m_acceleration.setEditable(false);
m_acceleration.setBackground(Color.black);
m_acceleration.setForeground(Color.white);
m_professionalism = new JTextField(2);
m_professionalism.setEditable(false);
m_professionalism.setBackground(Color.black);
m_professionalism.setForeground(Color.white);
m_jump = new JTextField(2);
m_jump.setEditable(false);
m_jump.setBackground(Color.black);
m_jump.setForeground(Color.white);
m_stamina = new JTextField(2);
m_stamina.setEditable(false);
m_stamina.setBackground(Color.black);
m_stamina.setForeground(Color.white);
m_bravery = new JTextField(2);
m_bravery.setEditable(false);
m_bravery.setBackground(Color.black);
m_bravery.setForeground(Color.white);
m_fitness = new JTextField(2);
m_fitness.setEditable(false);
m_fitness.setBackground(Color.black);
m_fitness.setForeground(Color.white);
m_experience = new JTextField(2);
m_experience.setEditable(false);
m_experience.setBackground(Color.black);
m_experience.setForeground(Color.white);
//create a panel to hold this data
Panel data = new Panel();
data.setLayout(new GridLayout(0,4));
data.setBackground(Color.blue);
data.add(m_labelname);
data.add(m_name);
data.add(m_labelage);
data.add(m_age);
data.add(m_labelweight);
data.add(m_weight);
data.add(m_labelspeed);
data.add(m_speed);
data.add(m_labelacceleration);
data.add(m_acceleration);
data.add(m_labelprofessionalism);
data.add(m_professionalism);
data.add(m_labeljump);
data.add(m_jump);
data.add(m_labelstamina);
data.add(m_stamina);
data.add(m_labelbravery);
data.add(m_bravery);
data.add(m_labelfitness);
data.add(m_fitness);
data.add(m_labelexperience);
data.add(m_experience);
getContentPane().add(data, BorderLayout.CENTER);
public void buildDefaultGUI() //construct the default components for GUI
JToolBar wndToolBar = new JToolBar();
wndToolBar.setBackground(Color.green);
wndToolBar.setFloatable(false);
m_buttonFirst = new JButton( new ImageIcon( "graphic/myFirst.gif" ) );
m_buttonPrevious = new JButton(new ImageIcon( "graphic/myPrevious.gif" ) );
m_buttonNext = new JButton(new ImageIcon( "graphic/myNext.gif" ) );
m_buttonLast = new JButton(new ImageIcon( "graphic/myLast.gif" ) );
m_buttonClose = new JButton(new ImageIcon( "graphic/myClose.gif" ) );
m_mainbuttonClose = new JButton("CLOSE");
// implement action listener
m_buttonFirst.addActionListener(this);
m_buttonPrevious.addActionListener(this);
m_buttonNext.addActionListener(this);
m_buttonLast.addActionListener(this);
m_buttonClose.addActionListener(this);
m_mainbuttonClose.addActionListener(this);
//set the tool tips for each of the button
m_buttonFirst.setToolTipText( "Display first record" );
m_buttonPrevious.setToolTipText( "Display previous record" );
m_buttonNext.setToolTipText( "Display next record" );
m_buttonLast.setToolTipText( "Display last record" );
m_buttonClose.setToolTipText( "Close this window and return to game" );
m_mainbuttonClose.setToolTipText( "Close this window and return to game" );
m_mainbuttonClose.setBackground(Color.green);
//add these buttons to the toolbar
wndToolBar.add( m_buttonFirst );
wndToolBar.add( m_buttonPrevious );
wndToolBar.add( m_buttonNext );
wndToolBar.add( m_buttonLast );
wndToolBar.addSeparator(); //separator in the toolbar
wndToolBar.add( m_buttonClose );
getContentPane().add(wndToolBar, BorderLayout.NORTH);
getContentPane().add(m_mainbuttonClose, BorderLayout.SOUTH);
public void buildCourseGUI() //construct the course GUI
buildDefaultGUI();
public void buildJockeyGUI() //construct the jockey GUI
buildDefaultGUI();
public void actionPerformed( ActionEvent evt)
//button first record is pressed
if( evt.getSource() == m_buttonFirst )
try
if( m_DatabaseMan.m_resultSet.first() )
transferData(type1);
catch (SQLException exSQL )
System.err.println( exSQL.toString() );
//button next record is pressed
if( evt.getSource() == m_buttonNext )
try
if(!m_DatabaseMan.m_resultSet.isLast())
if(m_DatabaseMan.m_resultSet.next())
transferData(type1);
catch (SQLException exSQL )
System.err.println( exSQL.toString() );
//previous button is pressed
if( evt.getSource() == m_buttonPrevious )
try
if( !m_DatabaseMan.m_resultSet.first())
if(m_DatabaseMan.m_resultSet.previous())
transferData(type1);
catch (SQLException exSQL )
System.err.println( exSQL.toString() );
//last button is pressed
if( evt.getSource() == m_buttonLast )
try
if(m_DatabaseMan.m_resultSet.last())
transferData(type1);
catch (SQLException exSQL )
System.err.println( exSQL.toString() );
// close button(s) pressed
if( evt.getSource() == m_buttonClose)
setVisible( false );
dispose(); //return the dialog window resources
m_DatabaseMan.CloseConnection();
if( evt.getSource() == m_mainbuttonClose)
setVisible( false );
dispose(); //return the dialog window resources
m_DatabaseMan.CloseConnection();
public void transferData(String type1) throws SQLException //return a String
if(type1 =="Horse")
//transfer horse details
m_name.setText(m_DatabaseMan.m_resultSet.getString("NAME"));
m_professionalism.setText(m_DatabaseMan.m_resultSet.getString("PROFESSIONALISM"));
m_speed.setText(m_DatabaseMan.m_resultSet.getString("SPEED"));
m_stamina.setText(m_DatabaseMan.m_resultSet.getString("STAMINA"));
m_weight.setText(m_DatabaseMan.m_resultSet.getString("WEIGHT"));
m_experience.setText(m_DatabaseMan.m_resultSet.getString("EXPERIENCE"));
m_fitness.setText(m_DatabaseMan.m_resultSet.getString("FITNESS"));
m_jump.setText(m_DatabaseMan.m_resultSet.getString("JUMP"));
m_age.setText(m_DatabaseMan.m_resultSet.getString("AGE"));
m_bravery.setText(m_DatabaseMan.m_resultSet.getString("BRAVERY"));
m_acceleration.setText(m_DatabaseMan.m_resultSet.getString("ACCELERATION"));
if(type1 =="Jockey")
m_name.setText(m_DatabaseMan.m_resultSet.getString("NAME"));
m_age.setText(m_DatabaseMan.m_resultSet.getString("AGE"));
if(type1 =="Course")
//transfer course details not implemented yet
} //end of class DBviewer
I ve set up an odbc driver and the database has data in it but I still get this run time error an no data is transfered to the dialog box
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1525)
at sun.jdbc.odbc.JdbcOdbcResultSet.reWordAsCountQuery(JdbcOdbcResultSet.java:6268)
at sun.jdbc.odbc.JdbcOdbcResultSet.calculateRowCount(JdbcOdbcResultSet.java:6061)
at sun.jdbc.odbc.JdbcOdbcResultSet.initialize(JdbcOdbcResultSet.java:150)
at sun.jdbc.odbc.JdbcOdbcStatement.getResultSet(JdbcOdbcStatement.java:420)
at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(JdbcOdbcStatement.java:250)
at DatabaseMan.<init>(DatabaseMan.java:34)
at DBviewer.<init>(DBviewer.java:83)
at MainWindow.actionPerformed(MainWindow.java:266)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1450)
at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1504)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:378)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:250)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:216)
at java.awt.Component.processMouseEvent(Component.java:3715)
at java.awt.Component.processEvent(Component.java:3544)
at java.awt.Container.processEvent(Container.java:1164)
at java.awt.Component.dispatchEventImpl(Component.java:2593)
at java.awt.Container.dispatchEventImpl(Container.java:1213)
at java.awt.Component.dispatchEvent(Component.java:2497)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:2451)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:2216)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2125)
at java.awt.Container.dispatchEventImpl(Container.java:1200)
at java.awt.Window.dispatchEventImpl(Window.java:914)
at java.awt.Component.dispatchEvent(Component.java:2497)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:339)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:131)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:98)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:85)
Im really stuck!!! any suggestions? thanks in advanceThank you for your response and sorry for the length
of code,
Thats was my first idea that it was asking for
or something I dont have but I checked my database and
I dont have any unusually large data entries (most
between 8-15 letters, the others are numbers) could it
be something wrong with how I've entered the database
in MsAccess, or am i barking up the wrong tree again!
Many thanks
RobI think you've misunderstood me. This has nothing to do with unusually large data entries, but rather the opposite. You are wrongly expecting data that is shorter than you think. When you call rs.getString(i) to retrieve a column value of a field, and you only want the first 5 characters in the column (instead of 10 or whatever the column size is), you would do something similar to the following:
String column_value = rs.getString(1).subtstring(0,5);The above expects a String that is at least 5 characters. Your problem is when your column value returned is less than the specified substring index ( in this case 5 ) it will throw an exception. If you changed your code to this, the error will not occur:
String column_value = rs.getString( 1 ).subtstring( 0, 5);
if ( column_value.length() > 5 )
column_value = column_value.substring( 0, 5 );
}Jamie -
Newbie: Problem with jdbc-odbc and MS SQL server 2005
I'm on win vistax64 with SQLSERVER 2005 and I have set up the odbc source as system dsn using the SQL Native Client driver with SQL authentication and the connectivity test in the end succeeds.
I'm trying to make a simple web app that will connect to the database and perform simple querries. It's a school assignment.
I'm using the jdbc-odbc bridge because it's the simplest way to do it and it's what we were shown in class.
I get the following irritating error:
"Cannot establish a connection to jdbc:odb:sstmdb using sun.jdbc.odbc.JdbcOdbcDriver ([Microsoft][ODBC Driver Manager] Data source name not found and no default driver specifies)".
I'm working with netbeans 5.5.1 and this error is what I get when in the runtime tab I try to connect with the jdbc-odbc. I get a similar error in the logs when I try to run the app on the j2ee server.
This is the java class that establishes the connection.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connector {
private static final String dbUrl="jdbc:odbc:sstmdb";
private static final String user="kimon";
private static final String password="jackohara";
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(dbUrl,user,password);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
return conn;
}It has worked perfectly on my school PC with winXP and MSDE2000.
What am I missing?Ok, help came from an other way where I was inquiring about a different problem:
Connectivity works fine by using User DSN instead of System DSN for the ODBC source.
Maybe you are looking for
-
Please help me for icloud activation ???
Hello if the device is locked on any Cloud for more than four months is not a closure device or reporting that he stole should not consider your esteemed company this subject because I began to hate Apple this reason please help my devise and activat
-
Hi.....Iam having prbs in redeeming the gift cards in iPod touch....my account is without credit card.....is this the prb???and wht to do pls help thanks
-
Line item and header records in the same infopackage
Gurus, I wanted to check how can I make sure that I get all the line item documents in the same package with the header document record in the same infopackage? Is there some setting for that? If I am writing a custom extractore how can I make sure o
-
Hey guys not gunna start saying BT promised this and that just looking for a bit of advice. For the last year or so my speed has been a pretty constant 63Mb I check it often with the Bras checker. Suddenly a few weeks ago it went UP to 69Mb (download
-
ADF : valueChangeListener is not working on checkbox
Hi All, I am using the following piece of code in ADF and valueChangeListener() associated to my check box is not working. Here is the piece of code : <af:selectBooleanCheckbox label="Budgetary Calendar" id="sbc1" selected="false" valueChangeListener