Mysql, jdbc, tomcat, jsp...
hi,
i am new in this topic.
i have some simple questions:
i use windows. i downloaded eclipse wtp, mysql 5.0.41, apache tomcat 6.0.13 and installed them all.
what version of jdbc should i download and what are the steps for a working connection between jsp and mysql?
what is the code that i should copy on the classpath?
where is classpath?
i know it is very boring for you but if you could help i would be so pleased:)
thank you..
what version of jdbc should i download JDBC is just available in the JDK.
If you mean the JDBC driver, the Connector/J, just refer to the manfacturer's site.
Here is a link: http://www.mysql.com/products/connector/j/
For Java 1.5 (JDBC 3.0), get the Connector/J 5.0.
For Java 1.6 (JDBC 4.0), get the Connector/J 5.1.
and what are the steps for a working connection between jsp and mysql?
what is the code that i should copy on the classpath?Read the reference manual available at the Connector/J site.
http://dev.mysql.com/doc/refman/5.0/en/connector-j.html
where is classpath?It depends on the running environment. As you're using Eclipse, just rightclick at the project, choose Properties, navigate to Java Build Path, choose tab Libraries and add the JAR to the classpath.
Similar Messages
-
MySQL(JDBC) with JSP error
Hello all,
I'm using MySQL 4.1.1 with JConnector 3.1 or 3.0, and I getting a unexpected result.
Fetching unicode strings with function ResultSet.getString(), returning "????" instead of Hebrew unicode chars ("אבגד").
As in PHP with the same DB, everything is working well.
When trying to use InputStream of the CLOB, or BLOB, the result comes good.
Does I need to declare something inorder to use unicode chars with the JDBC?
I'm connecting in a normal method, so I didn't post any code...when you start the server, you can specify unicode, something like this:
mysqld --unicodelanguage char set
look into the manu. -
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/ -
I think this is just a directory structure issue but I can't figure it out. I am writing a JSP / Struts / MYSQL web application which uses the mysql JDBC connector. The connector (mysql-connector-java-5.1.6-bin.jar) is in the referenced libraries. If I write the line of code:
Class.forName("com.mysql.jdbc.Driver");
To load up the driver, it works in JSP files in the folder /projectname/webroot/web-inf just fine and I can go on to execute MySQL queries. However, I need to load up the driver in an action (.java action) with the directory structure /projectname/src/action and it throws the exception "class not found", I believe, it can no longer seem to get to the driver. Can anyone tell me how to resolve this problem?
Thanks in advance, I hope this is the correct place (I have done my best to find the right one).
Edited by: Arkanin on Apr 24, 2008 4:39 PMArkanin wrote:
I think this is just a directory structure issue but I can't figure it out. I am writing a JSP / Struts / MYSQL web application which uses the mysql JDBC connector. The connector (mysql-connector-java-5.1.6-bin.jar) is in the referenced libraries. Nope, it's not. I don't know what "referenced libraries" means. It has to be in CLASSPATH, and that isn't an environment variable.
If I write the line of code:
Class.forName("com.mysql.jdbc.Driver"); No, wrong.
The JAR file for the Driver class might go in the WEB-INF/lib of your web app. If you're using Tomcat 5.5.26, put it in common/lib.
% -
Tomcat com.mysql.jdbc.NotImplemented error in the first launch
I created a war in java studio creator2 , export war file and deploy it by TomCat manager, After that ,when I launch a page at the first time , I got the following error
com.sun.rave.web.ui.appbase.ApplicationException: org.apache.jasper.JasperException: java.lang.RuntimeException: com.mysql.jdbc.NotImplemented: Feature not implemented
com.sun.rave.web.ui.appbase.faces.ViewHandlerImpl.destroy(ViewHandlerImpl.java:601)
com.sun.rave.web.ui.appbase.faces.ViewHandlerImpl.renderView(ViewHandlerImpl.java:316)
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:87)
com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:221)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:117)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:198)
com.sun.rave.web.ui.util.UploadFilter.doFilter(UploadFilter.java:194)
If I launch the same page again , this problem does not ocurr and the jsp page work normaly , it can access the database without any problem
Right now , I am using Tomcat 5.0.28 , js2dk_1.4.2_04,mysql 4.0.16 , SuSe 8.0 , java studio creator 2
jdbc driver class :org.gjt.mm.mysql.Driver
url : jdbc:mysql://192.168.100.151/mangomaximo
I have read many journal in this forums and I have follow the some of the instruction to try many time , but still failed .
Could anyone help me ?
ThanksHi,
See this "Deployment Example: Tomcat" might still helps
http://developers.sun.com/prodtech/javatools/jscreator/reference/docs/help/deploy/howtodeploy/deploy_tomcat.html
MJ -
Problem with JBDC connection to mysql in tomcat
hi ,
can anyone plz help me?..
iam new to JSP. iam trying to impelement a application in JSP with JDBC connection using tomcat. Database is MYSQL .
iam getting the following error:
org.apache.jasper.JasperException: Unable to get connection, DataSource invalid: "org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Server connection failure during transaction.
Attempted reconnect 3 times. Giving up.)"
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:510)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:375)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
root cause
javax.servlet.ServletException: Unable to get connection, DataSource invalid: "org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Server connection failure during transaction.
Attempted reconnect 3 times. Giving up.)"
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:858)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:791)
org.apache.jsp.test_jsp._jspService(test_jsp.java:81)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:332)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
THIS IS MY APPLICATION:
<html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<sql:query var="rs" dataSource="jdbc/TestDB">
select id, foo, bar from testdata
</sql:query>
<html>
<head>
<title>DB Test</title>
</head>
<body>
<h2>Results</h2>
<c:forEach var="row" items="${rs.rows}">
Foo ${row.foo}
Bar ${row.bar}
</c:forEach>
</body>
</html>
Following is the context file called "DBtest.xml" stored in webapps/DBtest/META-INF folder( i have a same copy of the file in /conf/Catelina/localhost)
<Context path="/DBTest" docBase="DBTest"
debug="5" reloadable="true" crossContext="true">
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/javatest?autoReconnect=true"/>
</Context>
i have following web.xml file in webapps/DBtest/WEB-INF
<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">
<description>MySQL Test App</description>
<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>
</web-app>
i have been refering to the internet form past 3 days and making lot of changes.but,there is no use.
plz guide me
thanksPerhaps a stupid question: is MySQL running and listening on port 3306? The problem is not always in the webapp. Perhaps you can create a small test class that uses Driver to make a connection to your database.
-
Problem Loading JDBC Enabled JSP Page
Hi all, does anyone knows that's the case of this error:
This happened when I tried to access MySQL Database from remote client. I have no problem loading normal jsp file w/o JDBC Connection. Kind of confused on what is going on
Regards,
Joe
HTTP Status 500 -
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: com.mysql.jdbc.Driver
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:254)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2415)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:171)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:594)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:392)
at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:565)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:619)
at java.lang.Thread.run(Thread.java:536)
root cause
javax.servlet.ServletException: com.mysql.jdbc.Driver
at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:536)
at org.apache.jsp.dbquery_jsp._jspService(dbquery_jsp.java:112)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:137)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:210)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2415)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:171)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:594)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:392)
at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:565)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:619)
at java.lang.Thread.run(Thread.java:536)
Apache Tomcat/4.1.24Hi scsi-boy, first of all, thank you so much for your
prompt and fast response. So how do i tackle
ClassNotFoundException ?.i'm sorry coz i'm a newbie to
jsp. I hope by providing my configuration below could
aid you in understanding my problem.
I've place the setting config in /etc/profile with the
following:
JAVA_HOME=/usr/local/java
CATALINA_HOME=/usr/local/tomcat
ANT_HOME=/usr/local/ant
APACHE_HOME=/usr/local/apache
MYSQL_HOME=/usr/local/mysql
CLASSPATH=${CATALINA_HOME}/common/lib/servlet-api.jar:$
YSQL_HOME/connector/mysql_connector/mysql_connector-jav
-3.08-stable-bin.jar:${JAVA_HOME}/lib/tools.jar:${JAVA_
OME}/jre/lib/rt.jar:./
PATH=${PATH}:${JAVA_HOME}/bin:${ANT_HOME}/bin:
MANPATH=${JAVA_HOME}/man:${MANPATH}
export JAVA_HOME ANT_HOME APACHE_HOME MYSQL_HOME
CATALINA_HOME CLASSPATH PATH MANPATH
As you can see, i've un-tar mysql_connector in
/usr/local/mysql/connector directory and set my
classpath to point to that file. Is that the proper
way to do it?
Regards,
Joesorry not a JSP expert however just to clarify i am guessing that it is a ClassNotFoundException. it could be something else entirely and i don't really want to send you on a wild goose chase. we need to know what the root exception actually is.
i am off to sleep now but i'm sure if you can give a little more information which may involve figuring out how to get it to cough up more information someone will help you here. -
How to connect .... MYSQL database via JSP
Hello,
I am not able to connect mysql database via JSP... everytime i try to connect the database i get the following error .....
"java.lang.NoClassDefFoundError: org/aspectj/lang/Signature" ..
my jsp code is ....
<%@ page import = "java.sql.*" %>
<%
Connection conn = null;
Statement smt = null;
ResultSet rs = null;
%>
<%
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase","username" ,"password");
smt = conn.createStatement();
rs = smt.executeQuery("select * from table");
out.println("output is "+ rs.getString("my field"));
rs.close();
%>
I have installed ............
jdk1.5.0_02
MySQL Server 4.1
there are two jar files .. i tried with both jar files ..
mysql-connector-java-3.1.8-bin.jar
mysql-connector-java-3.1.8-bin-g.jar
tomcat server 5.5.9
my path .... is
C:\Program Files\Java\jdk1.5.0_02\bin;C:\jakarta-tomcat-5.5.9\bin;C:\program files\mysql\mysql server 4.1\bin;
any help on this error ..at the earliest ..
... am worried ..bcoz my deadlines is getting closer .....
.. step by step .. procedure .. could be helpful ..
anilFind out the JAR which contains the class and add it
to WEB-INF/classes directory for your web application.WEB-INF/classes directory ..means ..C:\jakarta-tomcat-5.5.9\common\classes .. is that the one i need to keep my jar files ....???????????
well i have downloaded .. mysql database connector from the website "http://www.mysql.com/products/connector/j/ " .. and i have downloaded MySQL Connector/J 3.1..under which i have downloaded "Source and Binaries (zip)" ..
anil -
<%@ page import = "java.io.*, java.util.*,java.net.URL,java.awt.*,java.lang.*,java.sql.*" %>
<HTML>
<head></head>
<body>
<%
ResultSet rs;
Statement stmt;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/petrofed?user=petrofed&password=petro");
String sql = "SELECT * FROM sample";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next())
out.println(rs.getString(1));
out.println(rs.getString(2));
// Do something with the Connection
} catch (SQLException ex) {
// handle any errors
out.println("SQLException: " + ex.getMessage());
out.println("SQLState: " + ex.getSQLState());
out.println("VendorError: " + ex.getErrorCode());
catch (ClassNotFoundException cnfex)
out.println("SQLException: " + cnfex.getMessage());
%>
</body>
</html>
Getting following error after uploading it on the Server
SQLException: Communications link failure due to underlying exception: ** BEGIN NESTED EXCEPTION ** java.security.AccessControlException MESSAGE: access denied (java.net.SocketPermission localhost resolve) STACKTRACE: java.security.AccessControlException: access denied (java.net.SocketPermission localhost resolve) at java.security.AccessControlContext.checkPermission(AccessControlContext.java:269) at java.security.AccessController.checkPermission(AccessController.java:401) at java.lang.SecurityManager.checkPermission(SecurityManager.java:524) at java.lang.SecurityManager.checkConnect(SecurityManager.java:1023) at java.net.InetAddress.getAllByName0(InetAddress.java:1000) at java.net.InetAddress.getAllByName0(InetAddress.java:981) at java.net.InetAddress.getAllByName(InetAddress.java:975) at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:133) at com.mysql.jdbc.MysqlIO.(MysqlIO.java:281) at com.mysql.jdbc.Connection.createNewIO(Connection.java:1696) at com.mysql.jdbc.Connection.(Connection.java:408) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:270) at java.sql.DriverManager.getConnection(DriverManager.java:512) at java.sql.DriverManager.getConnection(DriverManager.java:193) at org.apache.jsp.mysqldb2_jsp._jspService(mysqldb2_jsp.java:59) at org.apache.jasper.runtime.HttpJspBase.service(Unknown Source) at javax.servlet.http.HttpServlet.service(HttpServlet.java) at org.apache.jasper.servlet.JspServletWrapper.service(Unknown Source) at org.apache.jasper.servlet.JspServlet.serviceJspFile(Unknown Source) at org.apache.jasper.servlet.JspServlet.service(Unknown Source) at javax.servlet.http.HttpServlet.service(HttpServlet.java) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Unknown Source) at org.apache.catalina.core.ApplicationFilterChain.access$0(Unknown Source) at org.apache.catalina.core.ApplicationFilterChain$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at org.apache.catalina.core.ApplicationFilterChain.doFilter(Unknown Source) at org.apache.catalina.core.StandardWrapperValve.invoke(Unknown Source) at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(Unknown Source) at org.apache.catalina.core.StandardPipeline.invoke(Unknown Source) at org.apache.catalina.core.ContainerBase.invoke(Unknown Source) at org.apache.catalina.core.StandardContextValve.invoke(Unknown Source) at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(Unknown Source) at org.apache.catalina.core.StandardPipeline.invoke(Unknown Source) at org.apache.catalina.core.ContainerBase.invoke(Unknown Source) at org.apache.catalina.core.StandardContext.invoke(Unknown Source) at org.apache.catalina.core.StandardHostValve.invoke(Unknown Source) at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(Unknown Source) at org.apache.catalina.valves.ErrorDispatcherValve.invoke(Unknown Source) at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(Unknown Source) at org.apache.catalina.valves.ErrorReportValve.invoke(Unknown Source) at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(Unknown Source) at org.apache.catalina.core.StandardPipeline.invoke(Unknown Source) at org.apache.catalina.core.ContainerBase.invoke(Unknown Source) at org.apache.catalina.core.StandardEngineValve.invoke(Unknown Source) at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(Unknown Source) at org.apache.catalina.core.StandardPipeline.invoke(Unknown Source) at org.apache.catalina.core.ContainerBase.invoke(Unknown Source) at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:594) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:392) at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:565) at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:619) at java.lang.Thread.run(Thread.java:534) ** END NESTED EXCEPTION ** SQLState: 08S01 VendorError: 0Tomcat is running with a Java security manager that doesn't let your application connect via sockets to applications outside Tomcat. You could perhaps fix this by configuring Tomcat with a security policy that does permit that, but don't ask me how to do that. I would fix the problem by using connection pools that are (I believe) built into Tomcat.
-
Cannot load JDBC driver class 'com.mysql.jdbc.Driver'
Hi,
At the moment I'm trying to get an example working. The error message I get is:
Unable to get connection, DataSource invalid: "org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot load JDBC driver class 'com.mysql.jdbc.Driver'"
The example I tried is http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html.
Configuration:
Wampserver 2.0 (Apache, MySQL, PHP for Windows XP), Tomcat 6.0 and jdk1.6.0_03.
The following files are installed in %CATALINA_HOME%/webabbs/
- Dbtest/test.jsp
- Dbtest/WEB-INF/web.xml
- Dbtest/WEB-INF/lib/standard.jar
- Dbtest/WEB-INF/lib/tomcat-dbcp.jar
- Dbtest/WEB-INF/lib/jstl.jar
Tia,
Abel.Hi,
I added the jar file containing the requested class to my lib directory. So the current contents of that directory is:
The following files are installed in %CATALINA_HOME%/webabbs/
- Dbtest/test.jsp
- Dbtest/WEB-INF/web.xml
- Dbtest/WEB-INF/lib/standard.jar
- Dbtest/WEB-INF/lib/tomcat-dbcp.jar
- Dbtest/WEB-INF/lib/jstl.jar
- Dbtest/WEB-INF/lib/mysql-connector-java-5.1.5-bin.jar
More importantly, I started my Wamp server.
The example works as it should have. Thanks for the feedback.
Abel -
No suitable driver with com.mysql.jdbc.Driver
Ok. here's the issue. I have a windows box. (first problem) but let's pretend that it's ok. :) I installed Tomcat 4.1 installed J2SDK1.4.0
start serving pages GREAT!. I have Mysql working perfectly with PHP on this system. I JUST want to connect with JDBC :)
I've downloaded the MySQL Jdbc Connector/J 3.08 stable installed the .jar file in the $JAVA_HOME/jre/lib/ext as per the README
Now granted I am a little new to JSP. but I have checked over this again and again. used different code. connected as many ways as I can think of and I still get the same result.
Database Error :
No suitable driver
Please Try Some Other Time
So I figure it's a MYSQL issue. no I also went thru and did the Microsot connection to MS SQL 2000 with the same result.
Here's where the drivers are (tried using the other method for installing the MySQL connector as well, and my class path
Y:\j2sdk1.4.0\com\mysql\jdbc\Driver.class
com.mysql.jdbc.Driver.class
Y:\j2sdk1.4.0\org\gjt\mm\mysql\Driver.class
org.gjt.mm.mysql.Driver.class
My classpath is:
.;F:\j2sdk1.4.0\;F:\j2sdk1.4.0\bin\;F:\j2sdk1.4.0\lib\;F:\j2sdk1.4.0\lib\classes\
[ Here's The Enviorment]
Windows 2000 5.00.2195 SP3
MS SQL 2K SP3
Apache Tomcat/4.1.27
j2sdk1.4.0
MySql 3.23.57-nt
mysql Jdbc Connector/J 3.08 stable
<!-- mysql.jsp BEGIN-->
<%@ page import="java.sql.*" %>
<%
Connection conn;
ResultSet results;
try {
String jdbc_driver = "com.mysql.jdbc.Driver";
System.out.println("jdbc_driver = " + jdbc_driver);
Class.forName(jdbc_driver).newInstance();
catch (ClassNotFoundException cnfe)
System.out.println(cnfe.getMessage());
try {
String url = "jdbc:mysql://localhost:3306/javatest?username=root,password=****"; // pass hidden
conn = DriverManager.getConnection(url);
System.out.println("connected to mySql DataBase");
Statement stmt = conn.createStatement();
Statement smt=conn.createStatement();
results=smt.executeQuery("select * from testdata");
while(results.next())
%>
<%= results.getString("foo")%>
<%= results.getString("bar")%>
<%= results.getString("id")%>
<%
results.close();
conn.close();
catch(Exception exp)
%>
<H3>Database Error : </H3><B><%= exp.getMessage() %></B><H3>Please Try Some Other Time</H3>
<%
%>
<!-- mysql.jsp end -->
BTW i aslo tried connecting to MicrosoftSQL 2K
<!-- microsoft.jsp Begin -->
<%@ page import="java.sql.*" %>
<%
Connection conn;
ResultSet results;
try {
String jdbc_driver = "sun.jdbc.odbc.JdbcObdcDriver";
System.out.println("jdbc_driver = " + jdbc_driver);
Class.forName(jdbc_driver).newInstance();
catch (ClassNotFoundException cnfe)
System.out.println(cnfe.getMessage());
try {
String url = "jdbc:odbc:contacts";
String username = "javauser";
String pw = "javauser";
conn = DriverManager.getConnection(url, username, pw);
System.out.println("connected to Msoft DataBase");
Statement stmt = conn.createStatement();
Statement smt=conn.createStatement();
results=smt.executeQuery("select * from contacts");
while(results.next())
%>
<%= results.getString("name")%><br>
<%
results.close();
conn.close();
catch(Exception exp)
%>
<H3>Database Error : </H3><B><%= exp.getMessage() %></B><H3>Please Try Some Other Time</H3>
<%
%>
<!-- microsoft.jsp end -->
got the exact same results.
Just to show you mysql is Good. with localhost.
mysql -u root -h localhost -p
mysql> use javatest
Database changed
mysql> select * from testdata;
| id | foo | bar |
| 1 | hello | 12345 |
1 row in set (0.00 sec)
mysql>Nope, it's not a MySQL issue.
I'd recommend NOT putting the JDBC JAR file (or any others, except Sun-sanctioned extensions) in JAVA_HOME/jre/lib/ext.
JDBC JARs belong in TOMCAT_HOME/common/lib or in the WEB-INF/lib directory for your particular app. If you put them in the former, all apps running under Tomcat can have access to them. If you put them in the latter, only your app can see them.
After you've done that, do some reading about JNDI data sources under Tomcat:
http://jakarta.apache.org/tomcat/tomcat-4.1-doc/jndi-datasource-examples-howto.html
That way you can get that connection code out of your JSPs and into the web.xml and <Context>, where it belongs. You'll be able to change data sources without rewriting your pages.
Good luck - MOD -
Error in Class.forName("com.mysql.jdbc.driver")
Hi forum,
Please help me to solve the issue.
im using the following jsp code for genrating the reports using JASPER REPORTS
the JSP FILE
<%@ page contentType="text/html;charset=windows-1252"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.DataSource"%>
<%@ page import="javax.naming.InitialContext"%>
<%@ page import="net.sf.jasperreports.engine.*"%>
<%@ page import="net.sf.jasperreports.engine.design.JasperDesign"%>
<%@ page import="net.sf.jasperreports.engine.xml.JRXmlLoader"%>
<%@ page import="net.sf.jasperreports.engine.export.*" %>
<%@ page import ="net.sf.jasperreports.engine.*"%>
<%@ page import ="net.sf.jasperreports.engine.JasperFillManager"%>
<%@ page import ="net.sf.jasperreports.engine.JRException"%>
<%@ page import="net.sf.jasperreports.engine.JasperReport"%>
<%@ page import="net.sf.jasperreports.engine.JasperPrint"%>
<html>
<body bgcolor="00ffcc">
<%
try{
Connection con = null;
String url="jdbc:mysql://localhost/customer";
String username = "root";
String password = "cmsadmin";
InputStream input=new FileInputStream(new File("C:/Documents and Settings/user/My Documents/NetBeansProjects/jasperreports/web/helloworld.xml"));
JasperDesign design = JRXmlLoader.load(input);
JasperReport report = JasperCompileManager.compileReport(design);
Map params = new HashMap();
params.put("reportTitle", "helloworld");
params.put("author", "Muthu Kumar");
params.put("startDate", (new java.util.Date()).toString());
params.put("ReportTitle", "PDF JasperReport");
<img class="emoticon" src="images/emoticons/confused.gif" border="0" alt="" />Class.forName("com.mysql.jdbc.Driver");<img class="emoticon" src="images/emoticons/confused.gif" border="0" alt="" /><img src="images/emoticons/confused.gif" border="0" alt="" />
con = DriverManager.getConnection(url,username,password);
JasperPrint print = JasperFillManager.fillReport(report, params, con);
OutputStream output=new FileOutputStream(new File("C:/Documents and Settings/user/My Documents/NetBeansProjects/jasperreports/helloreportworld.pdf"));
JasperExportManager.exportReportToPdfStream(print, output);
// JasperViewer.viewReport(print);
catch(SQLException es) {
out.println(es);
catch(JRException ex){
//ex.printStackTrace();
out.println(ex);
%>
</body>
</html>The error it is saying is in the line Class.forName(....) ;
Please look for the emoctions with question mark
i DOn know what to do.
Please help
Im comparin the below JRXML file as with the above code
<?xml version="1.0"?>
<!DOCTYPE jasperReport
PUBLIC "-//JasperReports//DTD Report Design//EN"
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport name="helloworld">
<parameter name="reportTitle" class="java.lang.String"/>
<parameter name="author" class="java.lang.String"/>
<parameter name="startDate" class="java.lang.String"/>
<queryString>
<![CDATA[SELECT * FROM customer order by UserID ]]>
</queryString>
<field name="UserID" class="java.lang.String"/>
<field name="UserName" class="java.lang.String"/>
<field name="City" class="java.lang.String"/>
<field name="State" class="java.lang.String"/>
<title>
<band height="60">
<textField>
<reportElement x="0" y="10" width="500" height="40"/>
<textElement textAlignment="Center">
<font size="24"/>
</textElement>
<textFieldExpression class="java.lang.String">
<![CDATA[$P{reportTitle}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x="0" y="40" width="500" height="20"/>
<textElement textAlignment="Center"/>
<textFieldExpression class="java.lang.String">
<![CDATA["Run by: " + $P{author}
+ " on " + $P{startDate}]]>
</textFieldExpression>
</textField>
</band>
</title>
<columnHeader>
<band height="30">
<rectangle>
<reportElement x="0" y="0" width="500" height="25"/>
<graphicElement/>
</rectangle>
<staticText>
<reportElement x="5" y="5" width="50" height="15"/>
<textElement/>
<text><![CDATA[UserID]]></text>
</staticText>
<staticText>
<reportElement x="55" y="5" width="150" height="15"/>
<text><![CDATA[UserName]]></text>
</staticText>
<staticText>
<reportElement x="205" y="5" width="255" height="15"/>
<text><![CDATA[City, State]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height="20">
<textField>
<reportElement x="5" y="0" width="50" height="15"/>
<textElement/>
<textFieldExpression class="java.lang.String">
<![CDATA[$F{UserID}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x="55" y="0" width="150" height="15"/>
<textElement/>
<textFieldExpression class="java.lang.String">
<![CDATA[$F{UserName}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x="205" y="0" width="255" height="15"/>
<textElement/>
<textFieldExpression class="java.lang.String">
<![CDATA[$F{City} + ", " + $F{State}]]>
</textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>Glass_Fish wrote:
I have set the classpath in the environment variables in the my computer properties.The web container has it's own properties. The "system" classpath means absolutely nothing to it. Read your server's documentation. -
I have read several threads, and others are having this problem but the resolutions do not seem to be posted or are different than what I am having. Hopefully someone can help me figure out...
Cannot create JDBC driver of class '' for connect URL 'null'
I verified that my url was correct here...
http://dev.mysql.com/doc/connector/j/en/cj-driver-classname.html
Here is my server.xml snippet
<GlobalNamingResources>
<Resource name="jdbc/mtshr" auth="Container"
type="javax.sql.DataSource" username="xxxx" password="xxxx"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mtshr?autoReconnect=true"
maxActive="8" maxIdle="4"/>
</GlobalNamingResources>
in my WEB-INF/web.xml
<resource-ref>
<description>
HRDB Deployment
</description>
<res-ref-name>
jdbc/mtshr
</res-ref-name>
<res-type>
javax.sql.DataSource
</res-type>
<res-auth>
Container
</res-auth>
</resource-ref>
I have tried moving the mysql-connector-java-3.1.7-bin.jar to both common/lib and WEB-INF/lib
My code to connect is...
java.sql.Connection Conn = null;
javax.sql.DataSource ds = null;
java.sql.Statement Stmt = null;
java.sql.ResultSet rs = null;
javax.naming.InitialContext ctx = new javax.naming.InitialContext();
javax.naming.Context envctx = (javax.naming.Context) ctx.lookup("java:comp/env");
ds = (javax.sql.DataSource) envctx.lookup("jdbc/mtshr");
Conn = ds.getConnection();
Stmt = Conn.createStatement();
(delete these last two statements and no errors)
Any help is GREATLY appreciated. I had everything running in TC 3.2.3 and 4.1 I thought it would be a good idea and exercise to revisit my code and get some experience with j2se 5.0 and TC 5.5
Not promising if I can't even get past the setup :) Thanks again!SO...
I created a META-INF folder in my app, and then created a file called context.xml which contained the same code as I had in my server.xml file.
In the documentation http://localhost:8080/tomcat-docs/jndi-datasource-examples-howto.html#Common%20Problems
it says that you can use global naming instead of context. Didn't work with global naming but it did work with context. No idea why, just know that it did. -
Mm.mysql JDBC Driver and the WHERE clause
Anybody has succesfully performed a MySQL/JDBC query in a JSP application using more than one variable in the WHERE clause?
It works fine when I run queries with one fixed value assigned to a column and one variable assigned to the other column in the WHERE clause; but when I do it with more than one variable in the WHERE clause, it screws up throwing an error.
I wonder if it is a code error, a syntax error or if it is something tricky about the mm.mysql JDBC Driver. Following is a section of the code and the error. The variables are s_description and s_status. I read some examples in a book but they use SQL Server. Thank you in advance for any information.
CODE:
<% String sqlStatement = "" ; %>
<% String s_description = "Mexican Style Rice" ; %>
<% String s_status = "available" ; %>
<% java.sql.Statement stmt = con.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_UPDATABLE); %>
<% java.sql.ResultSet rs ; %>
<% sqlStatement = "SELECT code, description, status FROM products WHERE products.description =" + s_description + " AND products.status =" + s_status + ";" ;%>
<% rs = stmt.executeQuery(sqlStatement); %>
<% rs.beforeFirst(); %>
<% while (rs.next()) { %>
<% rs.updateString(3, "sold"); %>
<% rs.updateRow(); %>
<% }%>
<% rs.close(); %>
This is the ERROR it throws
java.sql.SQLException: Column not found: Unknown column 'available' in 'where clause'
at org.gjt.mm.mysql.MysqlIO.sendCommand(MysqlIO.java:497)
at org.gjt.mm.mysql.MysqlIO.sqlQueryDirect(MysqlIO.java:550)
at org.gjt.mm.mysql.MysqlIO.sqlQuery(MysqlIO.java:635)
at org.gjt.mm.mysql.Connection.execSQL(Connection.java:882)
at org.gjt.mm.mysql.Connection.execSQL(Connection.java:815)
at org.gjt.mm.mysql.Statement.executeQuery(Statement.java:169)
at org.gjt.mm.mysql.jdbc2.Statement.executeQuery(Statement.java:78)
at pagecompile._GetFood_xjsp._jspService(_GetFood_xjsp.java:45)
at com.newatlanta.servletexec.JSP10HttpJspPage.service(JSP10HttpJspPage.java:41)
at com.newatlanta.servletexec.JSP10Servlet.service(JSP10Servlet.java:779)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at com.newatlanta.servletexec.ServletExec.CallServletService(ServletExec.java:1679)
at com.newatlanta.servletexec.ServletExec.processServletRequest(ServletExec.java:1654)
at com.newatlanta.servletexec.ServletExec.processServletAlias(ServletExec.java:1602)
at com.newatlanta.servletexec.ServletExec.ProcessRequest(ServletExec.java:1343)
at com.newatlanta.servletexec.ServletExec.ProcessRequest(ServletExec.java:1113)I think perhaps this sentence has problems:
<% sqlStatement = "SELECT code, description, status FROM products WHERE products.description =" + s_description + " AND products.status =" + s_status + ";" ;%>
You can
<% sqlStatement = "SELECT code, description, status FROM products WHERE products.description ='" + s_description + "' AND products.status = '" + s_status + "'" ;%>
You perhaps ignore the ���� when using String variable s_description and s_status.
Hope this will help you. Good lucky! -
Accessing MySql database in jsp
hi everyone!!!
i m new to java with little knowledge of jsp.
i want to access mysql database in jsp to develop a web page.
i have jdk and mysql installed and these are working. what are other requirements and how to do this.
plz help.
OS: MS Windows XP/ Fedora 10Learn JDBC API: [http://java.sun.com/docs/books/tutorial/jdbc/index.html]. Create a DAO class which uses JDBC to interact with Java and takes or returns the desired data in form of DTO's. Use and test it as a plain vanilla Java application with a main() method. This require a JDBC driver (a concrete implementation of the JDBC API) in the classpath. MySQL offers JDBC drivers as download at their homepage, it is called "Connector/J".
Once you got the JDBC part to work, create a Servlet class which holds an instance of the DAO class and uses its methods to interact with the database. In the doGet() you can place logic to preload data from the DAO class for display. In the doPost() you can place logic to process data for create, update or delete using the DAO class. Finally let it forward the request to a JSP.
In the JSP you can use JSTL/EL to display data. For tabular view you may find the JSTL c:forEach useful. For plain display, just use EL the usual way.
Maybe you are looking for
-
How to create a primary key or foreign key
in the table student, sid should be the primary key in the table prerequisite cnum should be the foreign key and prereq the primary key please help me with the syntax thanks.
-
Cannot install Headstart 2.1.2 due to strange error.
I'm trying to install Headstart 2.1.2.0.2 on an Oracle 8.1.5.0.0 clean DB and Designer 6.0 After selecting a home in the installer and assigning a directory I want to install Headstart but the installer immediately errors out with the following messa
-
XML DB when you have a lot of XSDs....
My client has a data situation where we have a lot of XSD schemas (and multiple versions of each XSD) which describe data that needs to be loaded. If I wanted to use schema-based / structured-storage....Can the same xmltype column be mapped to multip
-
Hi, Using Adobe Reader 8.1.2 for Mac OS X and 8.* for Windows, my PDFs printed out identically for both platforms. However, after I upgraded Windows Adobe Reader from 8 to 9.0.0, it prints out the PDFs significantly darker than before, whereas when I
-
i downloaded lion but lost the setup assistant. please help me recover the setup assistant. i do not know where/how to find/enter information in the terminal as was suggested.