Connecting to a database in JSP
If I had an Access database called "testDB" which has no username or password, how would I go about connecting to it in JSP? I have a book but it's a little ambiguous. My code for my Bean to connect to a database is below, I just need to know how I can access it from a JSP page...
import java.sql.*;
public class DataSourceBean{
private static String url;
private static String username;
private static String password;
public void setDriver(String driver) throws ClassNotFoundException {
Class.forName(driver);
public void setUrl(String aUrl){
url=aUrl;
public void setUsername(String aUsername){
username=aUsername;
public void setPassword(String aPassword){
password=aPassword;
public static Connection getConnection() throws SQLException{
return DriverManager.getConnection(url, username, password);
}Thanks for any help.
Hi, This is Aykut Yararbas;
You already have what you need in your hand.
1. import the package that conations your DataSourceBean
<%@page import="com.package.DataSourceBean"%>
2. Import java.sql.* package as in (1)
3. Instantiate your class
<%DataSourceBean dsb = new DataSourceBean();
// Set the usr , pass, url
dsb.setUrl("jdbc:db2:testDb");
dsb.setUsername("username");
dsb.setPasssword("password");
//Ready to receive connection
Connection con = dsb.getConnection();
%>
This solves your question
But I do not advice implementing the data access at JSP level.
Similar Messages
-
Connecting to a database in JSP but using connection in bean
I have a bean which connects to a database which is as follows:
package MyPackage;
import java.sql.*;
public class DataSourceBean{
public DataSourceBean(){
public void setDriver(String driver) throws ClassNotFoundException {
Class.forName(driver);
public void setUrl(String aUrl){
url=aUrl;
public void setUsername(String aUsername){
username=aUsername;
public void setPassword(String aPassword){
password=aPassword;
public static Connection getConnection() throws SQLException{
return DriverManager.getConnection(url, username, password);
private static String url;
private static String username;
private static String password;
}I then connect to a database through my JSP page:
<jsp:useBean id="db" class="MyPackage.DataSourceBean" scope="application">
<jsp:setProperty name="db" property="driver" value="sun.jdbc.odbc.JdbcOdbcDriver" />
<jsp:setProperty name="db" property="url" value="jdbc:odbc:MyDB" />
</jsp:useBean>This opens the database for the session, but I then want to allow people to login using a seperate bean.
My question is how do I use the connection created in the JSP page above in my login bean?
I have also tried connecting to a database in my LoginBean by using:
DataSourceBean dsb=new DataSourceBean();
yet it doesn't recognise DataSourceBean for some reason.
BTW my book suggests opening up the database using scope="application" but to me it seems that keeping the database open is risky, is it OK to keep the database open for the whole session? do you have any other suggestions for accessing the database through my DataSourceBean?
Thanks for any help.hi shock,
there are a number of considerations when it comes to the database connections.
first of all is the database server yours or are you buying a hosting scheme?
if the database server is yours then you may consider building a database connection pool and keeping it in a session parameter. there's no harm in that because connections are opened as needed and closed when not needed. you can specify the minimum and maximum number of connections and connectio keep-alive times.
if you purchase your database from a host they possibly would object to having a db connection pool as connections are valuable for them. but in this case there is no harm to create a connection to the database per request because creating database connections are costly only for the database server. your application will not slow down that much.
for performance check sites: www.crystaltours.com or www.seckinkonaklar.com
in both sites all connections are created per request and the complete content (including menus and application properties) comes from the database.
my suggestion is that if you are writing a commercial application that will be hosted in a server that is not yours then create a connection per request (no pooling here).
i also would suggest to put your database access code in a single class -not in a bean- for easy maintenance, you can use that class in your beans.
i hope this was your answer.
cem. -
Trying to connect to a database via JSP
I'm trying to make a simple connection to a database called testbase but to no prevail. As you can see the code is really simple but i keep getting "javax.servlet.ServletException: Table 'testbase.testbase' doesn't exist".
//connection.jsp
<HTML>
<HEAD><TITLE>Employee List</TITLE></HEAD>
<BODY>
<%@ page import="java.sql.*" %>
<TABLE BORDER=1 width="75%">
<TR><TH>Data</TH></TR>
<%
Connection conn = null;
Statement st = null;
ResultSet rs = null;
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testbase",
st = conn.createStatement();
rs = st.executeQuery("select * from testbase");
%>
<TR><TD><%= rs.getString("table01") %></TD>
<TD><%= rs.getString("field01") %></TD></TR>
</BODY>
</HTML>
Can anyone find something wrong with the code or do you think that there's a connection problem someplace else?
Any replies are greatly appreciatedDriverManager.getConnection("jdbc:mysql://localhost:33
06/testbase",
st = conn.createStatement();
rs = st.executeQuery("select * from testbase");One of them or both might not be correct. Check if you have a database called testbase and it has a table called testbase.
You could login from MySQL command prompt with your login name and password (which I hope is not *) and check. -
Error in connecting to mysql database using jsp
Hi
I've encountered this error:
java.lang.ClassNotFoundException: org.gjt.mm.mysql.Driver
while trying to connect to MySQL db.
I've downloaded the driver from www.mysql.com, and set the classpath as: "C:\mm.mysql.jdbc-1.2b;%CLASSPATH%;"
But it juz doesn't seem to work...
Can someone pls help me?These are my settings in autoexec.bat:
SET PATH=C:\PROGRA~1\ABRIAS~1\ABRIAS~1\PERL\BIN;%PATH%;
SET JAVA_HOME=C:\jdk1.3.1
SET TOMCAT_HOME=C:\Tomcat3.2.3
SET CLASSPATH=C:\mm.mysql.jdbc-1.2b;%CLASSPATH%;
Well, i'm quite new to jsp so i'm not sure what u meant by "In the servlet container's init scripts?". I onli did the settings above and reset my server.
I've tried checking the dir...and yes there's a dir named org.
Any ideas wat can possibly be wrong??? -
I can't connect to MySQL database from The JSP Standard Tag Library
Hi All !
I have a problem, please help me anybody !
I don't connect to MySQL database from jsp page using JSTL tag but from servlet all work correctly. I set my path and put �mysql-connector-java-3.1.13-bin.jar� in ENVIRONMENT WinXP(classpath=C:\Java\jdk1.5.0_10\jre\lib\ext\mysql-connector-java-3.1.13-bin.jar) and in War project folder �WEB-INF/lib� and in [TomcatServer]\common\lib.
I have in folder�WEB-INF/lib� following files:
antlr.jar
commons-beanutils.jar
commons-collections.jar
commons-digester.jar
commons-fileupload.jar
commons-logging.jar
commons-validator.jar
jakarta-oro.jar
jsf-api.jar
jsf-impl.jar
jstl.jar
mysql-connector-java-3.1.13-bin.jar
standard.jar
struts.jar
I'm using:
NetBeans 5.5 Build200610171010 (bundled Tomcat 5.5.17)
Ent.Pack 20061020 Visual Wb Pack 061103
OS WinXP SP2
Java 1.5.0_10
MySQL 5.0.18-nt
1:<%@page contentType="text/html"%>
2:<%@page pageEncoding="UTF-8"%>
8: <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
9: <%@taglib uri="http://java.sun.com/jstl/sql" prefix="sql"%>
10:
11: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
12: "http://www.w3.org/TR/html4/loose.dtd">
13:
14: <sql:setDataSource var="ds"
15: driver="com.mysql.jdbc.Driver"
16: url="jdbc:mysql://localhost:3306/test"
17: user="root"
18: password="xxxx"/>
19:
20:
21:<sql:query sql="select name, age from People" var="res"
22: dataSource="${ds}"/>
I have received report on mistake when entered code at the top:
�/index.jsp [21;0] According to TLD or attribute directive in tag file, attribute dataSource does not accept any expressions�
I used instead of (dataSource="${ds}")->(dataSource="ds") but this did not work.
After build and run I have received
=========================================START=================================
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: /index.jsp(21,0) According to TLD or attribute directive in tag file, attribute dataSource does not accept any expressions
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)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
root cause
org.apache.jasper.JasperException: /index.jsp(21,0) According to TLD or attribute directive in tag file, attribute dataSource does not accept any expressions
org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:39)
org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:405)
org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:146)
org.apache.jasper.compiler.Validator$ValidateVisitor.checkXmlAttributes(Validator.java:955)
org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:710)
org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1441)
org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2163)
org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2213)
org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2219)
org.apache.jasper.compiler.Node$Root.accept(Node.java:456)
org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2163)
org.apache.jasper.compiler.Validator.validate(Validator.java:1489)
org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:166)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:295)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:276)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:264)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:563)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:303)
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)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
note The full stack trace of the root cause is available in the Apache Tomcat/5.5.17 logs.
Apache Tomcat/5.5.17
=======================================END================================
Error: "According to TLD or attribute directive in tag file, attribute dataSource does not accept any expressions" - but according to documentation such parameter possible.
BUT WHEN JOINING With DATABASE FROM SERVLET ALL WORK FINE.
I read this doc - [http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html], this applicable if I Tomcat Admin, but i'am not Admin
I simply user, i.e. I want to place its database on virtual host (Tomcat+(JSP-JSTL)+MySQL).
There is idea how can resolve this problem
Thank you in advance ;)For all how have similar problem.
Decision instead of these ways
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql" %>
it is necessary to indicate these
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -
Connection to the Database thru Servlet
Hello:
I have just read some threads in this forum and noticed that people saying that connecting to the database in JSP is not a good Java Programming Habit. So, could you please give a little guidance on connection to the Oracle database in servlet. Thank you very much.
Oscar.You use standard JDBC:
http://java.sun.com/docs/books/tutorial/jdbc/index.htmlIn a servlet container, most of the time, you set up a connection pool that you access through JNDI
http://jakarta.apache.org/tomcat/tomcat-5.0-doc/jndi-datasource-examples-howto.htmlFor larger applications you might want to use "Data Access Objects"
http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.htmlCheers,
evnafets -
Error while connecting to the database from a JSP Page
Hi,
I am using a simple JSP page which is based on the sample JSP pages from OTN.
When I try to connect to my database using the following code:
InitialContext ic = new InitialContext();
OracleDataSource ds = (OracleDataSource)ic.lookup("jdbc/OTN9iDS");
m_connection = ds.getConnection();
I get the following error:
Naming exception Error while connecting to the database : javax.naming.NameNotFoundException: jdbc/OTN9iDS not found in JDBCTest-JDBCTestProject-webapp
Does anybody know wht this is happening?
Any help would be appreciated
FRankHi Frank,
Are you using standalone OC4J or 9iAS ? If you are using standalone OC4J then you need to add a proper data source entry in %OC4J_HOME%j2ee\home\config\data-sources.xml file.
If you are using 9iAS the you can log in to the Enterprise Manager console and add the data source entry by using wizard provided by 9iAS.
Ensure the case of the JNDI lookup string, since, it is case sensitive.
Hope this helps.
Abhijeet -
Problem in connecting database in jsp.
I have oracle 7.3.4.0.1 I am trying to make a connection with oracle database. Following is the test.jsp file
<html>
<body bgcolor= white >
<%@ page language="java" import= "java.io.*"%>
<%@page import="javax.servlet.*"%>
<@page import="javax.servlet.http.*"%>
<@page import="java.util.*"%>
<@page import oracle.jdbc.driver.*"%>
<@page import java.math.*"%>
<%!Class.forName("oracle.jdbc.driver.OracleDriver").newInstance()%>
<%@page import="java.sql.*"%>
<%!Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@servername:1521:sid", "user", "password");;
Statement theStatement = conn.createStatement();
String s1 = SELECT name FROM arschema WHERE rownum<10;
// Query the Database
ResultSet theResults = theStatement.executeQuery(s1);
theResults.next();
%>
<table><tr><td><%=theResults.getString( name )%></td></tr>
</table>
<%
conn.close();
theStatement.close();
out.close();
%>
</body>
</html>
When I am viewing my jsp file in web browser, i am getting following error,
org.apache.jasper.JasperException: Unable to compile class for JSP/usr/local/apache/jakarta-tomcat-3.2.3/work/localhost_8080%2Fexamples/_0002ftest_0002ejsptest_jsp_0.java:21: Type expected.
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance()
^
1 error
on unix box i am getting following error at console
2001-10-18 16:23:12 - Ctx( /examples ): JasperException: R( /examples + /test.
jsp + null) Unable to compile class for JSP/usr/local/apache/jakarta-tomcat-3.2.
3/work/localhost_8080%2Fexamples/_0002ftest_0002ejsptest_jsp_0.java:21: Type exp
ected.
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance()
^
1 error
Please help
Thanks
Alka SrivastavI have made necessary modification in the code. Please take a look at it.
<html>
<body bgcolor= white >
<%@ page language="java" import= "java.io.*"%>
<%@page import="javax.servlet.*"%>
<@page import="javax.servlet.http.*"%>
<@page import="java.util.*"%>
<@page import oracle.jdbc.driver.*"%>
<@page import java.math.*"%>
<%!Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();%>
<%@page import="java.sql.*"%>
<%!Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@remdev1.kmct
elecom.com:1521:eftiap", "aradmin", "test1ora");
Statement theStatement = conn.createStatement();
String s1 = SELECT name FROM arschema WHERE rownum<10;
// Query the Database
ResultSet theResults = theStatement.executeQuery(s1);
theResults.next();
%>
<table><tr><td><%=theResults.getString( name )%></td></tr>
</table>
<%
conn.close();
theStatement.close();
out.close();
%>
</body>
</html>
Still getting following error. Where am I wrong.
2001-10-19 09:49:35 - Ctx( /examples ): JasperException: R( /examples + /test.
jsp + null) Unable to compile class for JSP/usr/local/apache/jakarta-tomcat-3.2.
3/work/localhost_8080%2Fexamples/_0002ftest_0002ejsptest_jsp_0.java:21: Type exp
ected.
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
^
1 error
Please help.
Thanks -
Connecting to a database from Business Components JSP Application
Hallo All!
Can anybody give me an advice about connecting to a database from Business Components JSP Application? In all examples I see that Oracle user name and password placed in configuration file.
How can user provide his own name and password to start Oracle session and how then hi can close this session?
null<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Dmitri:
Dear Laura,
I mean first variant where the database would be the same:
scott/tiger@database1
foo/bar@database1
Of course I understand that we must register every user in database by "CREATE USER XXX" and it is unacceptable for Internet. But it may be very convenient for an Intranet because we can build access restriction based on set of views without any changes in applications.
Best wishes,
Dmitri.<HR></BLOCKQUOTE>
null -
Hi guys Pls tell me a way to connect db4 database with jsp and which driver
hi guys
Pls tell me a way to connect db4 database with jsp and
also tell me which driver i have to use
also tell me how to connect with excel sheetstake a look at the follwing links. There, you'll find all what you need :
DB4:
http://www.oracle.com/database/berkeley-db/je/index.html
http://www.oracle.com/technology/products/berkeley-db/je/index.html
http://www.oracle.com/database/berkeley-db/db/index.html
http://www.oracle.com/database/docs/berkeley-db-je-datasheet.pdf
Excel:
http://64.18.163.122/rgagnon/javadetails/java-0516.html
Hope That Helps -
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 -
How to connect MySql database with JSP
Dear everyone,
how to connect MySql database with JSP......It's too bad that nobody has ever asked this question before...
-
How to connect to database in JSP
Hi, all.
I am using J2EE and cloudscape. I have written all the EJB classes. But now i have no idea that how to connect to database in jsp such as i get user ID from portal, then i connect to database check the existence of user ID and the password then return true or false value. how to write all this in jsp?
Thanks very much!
yayunthis is the required code
i hope this will help u
<html>
<head>
</head>
<body>
<%@ page import="java.sql.*" %>
<%
try
String fu=request.getParameter("username");
String fp=request.getParameter("password");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection Con=DriverManager.getConnection("jdbc:odbc:wind","","");
Statement stmt=Con.createStatement();
ResultSet rs=stmt.executeQuery("select * from table1 where username='"+fu+"' and password='"+fp+"'");
if(rs.next())
%>
<jsp:forward page="success.jsp"/>
<%
else{
%>
<jsp:forward page="unsuccess.jsp"/>
<%
catch(Exception e)
%>
</body>
</html> -
Connecting to MSAcess database using JDBC in JSP
Hi,
I have created an Aceess database file (C:\db1.mdb) and created a DSN=db1.
I could able to connect to the database and retrieve the information from the tables using Sun's JDBC OdBc bridge drivers.
DriverManager.getConnection("jdbc:odbc:db1").
It was working Fine in my Standalone java program.
But,when I used the database connection statements in my JSP page,it is not displaying any error message and not selecting rows from the Select statement i used in my JSP page.(The same worked in my standalone Java program).
I executed the two programs on same machine.Database is also on the same machine.
Can anyone tell me what shall i do to connect to the database(C:\db1.mdb) through JSP.
Thanks in Advance
Rao...in your code do you have any things that is suppressing your exception?? i.e. something lik
try
// do your stuff
catch(Exception e)
// do nothing??
}if so you vont get to know of any problem that happened....
also if there is an un handled exception the jsp page will sometimes come up as blank, because your print streem will be terminated abrubtly....
this will probably happen if you dont have a try - catch block at all, or if you are not handling the exception that is being thrown.... try inclosing your code in a try catch block and doing ex.priintStackTrace() in the catch block to get the exception trace on the server console....
also can you post some code for both your java client and jsp?? -
Connecting to database through jsp
i want to connect to database through jsp actually my requirement is i want to populate data in one list box in accordance with the selected option in another list box this must done in the same jsp and i must manupulate every thing java script can i found any solution to this with example
just write ur code in scriplets if it is jdbc code & if it is html then write it out side scriplet.
Maybe you are looking for
-
Can anyone help with Bluetooth and Audio output conflict?
Audio ouput from media files on Quicktime, Real Player and Windows Media will only play through my Bluetooth headset . I have tried resetting the Audio output preferences to no effect. Also tried reinstalling Bluetooth devices. When opening file the
-
How to maintain the sequence in the custom table
Hi, We have custom table where we will store the standard text name based on different flags and it will be fetched the value according to the condition. Example code SELECT SINGLE field1 field2 INTO ( vaiable1 variabl
-
Hi everyone, I am just curious to know when will Adobe AIR will be available for Mobiles. I came across on the web regarding "Open Screen Project" and lookin g forward for Adobe AIR to come on mobiles as there are lot of limitations in Flash lite per
-
Captivate 3 not sending correct completion information
Hi all, we are using Captivate 3, and are in the process of uploading our content to Element K's LMS. We have tested some of the content, and its marking courses complete even though the completion criteria have not been met. We have run through th
-
Help please with Format Advance
Hi everyone. I do themes with Intaglio, and drag over Keynote to do theme, but this drag is in .pdf, and when I select it in Keynote go Format >> Advance and see Picture...????, indeed of Figure. This form don't let me add Stroke or Fill in the cut-o