我试图做大量的 JSP 脚本来从数据库调用,然后我了解到这不是一个好主意,所以现在,我有点迷路了。
FirstExample.java:
package p;
//STEP 1. Import required packages
import java.sql.*;
public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "oracle.jdbc.OracleDriver";
static final String DB_URL = "url";
// Database credentials
static final String USER = "user";
static final String PASS = "pw";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("oracle.jdbc.OracleDriver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
// String sql;
ResultSet rs = stmt.executeQuery("some query");
System.out.println(rs);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
// int id = rs.getInt("some column");
System.out.println (rs.getString(1) + "," + rs.getString(2));
// int age = rs.getInt("some age");
// String first = rs.getString("first");
// String last = rs.getString("last");
//Display values
// System.out.print("some column: " + id);
// System.out.print(",some age: " + age);
// System.out.print(", First: " + first);
// System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
我需要将此结果输入 JDBCQuery2.jsp,其中显示:
<%@ page language="java" import="p.FirstExample" %>
<% FirstExample object = new FirstExample();
//FirstExample.init();
%>
<h3>Connection ok</h3>
这会正确加载包,但我需要 .java 中方法的结果,我不知道如何使用上面的 init 调用方法。我应该使用init吗?最终,我想将 java 引用与 ajax 调用相关联,但现在有人可以帮我将查询结果拉入我的 JSP 吗?任何帮助将不胜感激