jsp 查询Oracle数据库
2015-12-16 · 做真实的自己 用良心做教育
完整的JSP连接数据库的查询并显示
<%@page contentType="text/html;charset=gb2312"%>
<%@page import="java.sql.*"%>
<HTML><BODY>
<hr align="center" width="55%" color="#991111" size="5"/>
<%
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
request.setCharacterEncoding("GBK");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ce){
out.println(ce.getMessage());
}
try{
String url="jdbc:oracle:thin:@localhost:1521:orcl";
conn=DriverManager.getConnection(url,"scott","tiger");
stmt=conn.prepareStatement("select * from emp");
rs=stmt.executeQuery();
out.print("<TABLE BORDER='1' width='55%' cellpadding='3' align=center>");
out.print("<TR><TD>"+"<b>Empno</b>"+"</TD>");
out.print("<TD>"+"<b>Ename</b>"+"</TD>");
out.print("<TD>"+"<b>Job</b>"+"</TD>");
out.print("<TD>"+"<b>Mgr</b>"+"</TD>");
out.print("<TD>"+"<b>hiredate</b>"+"</TD>");
out.print("<TD align=center>"+"<b>Sal</b>"+"</TD>");
out.print("<TD>"+"<b>Comm</b>"+"</TD>");
out.print("<TD>"+"<b>Deptno</b>"+"</TD></TR>");
while(rs.next()){
out.print("<TR><TD>"+rs.getString(1)+"</TD>");
out.print("<TD>"+rs.getString(2)+"</TD>");
out.print("<TD> "+rs.getString(3)+"</TD>");
out.print("<TD>"+rs.getString(4)+"</TD>");
out.print("<TD>"+rs.getString(5)+"</TD>");
out.print("<TD>"+rs.getString(6)+"</TD>");
out.print("<TD>"+rs.getString(7)+"</TD>");
out.print("<TD>"+rs.getString(8)+"</TD></TR>");
}
out.print("</TABLE>");
rs.close();
stmt.close();
conn.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
%>
</BODY></HTML>
PreparedStatement pstmt = null;
ResultSet rs = null;
Connection conn = null ;
String sql = null;
int id;
%>
<%
sql = "select id from table1" //比如说读出id
try{
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD) ; pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next())
{
id = rs.getInt(1);
}
%>
<%=id%><br />
<%
}catch(Exception e){}
try
{ rs.close() ;
pstmt.close() ;
conn.close() ;
}catch(Exception e){}
%>
DBURL,DBUSER,DBPASSWORD分别是你的数据库地址,用户名,和密码!
这样就可以了!