jsp怎么连接数据库oracle

2024-12-04 07:28:43
推荐回答(1个)
回答1:

JSP连接Oracle10g数据库的方法:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>


Oracle数据库连接测试


<%
java.sql.Connection lConn = null;
java.sql.Statement lStat = null;
java.sql.ResultSet lRs = null;
try
{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
String lUrl = "java:oracle:thin:@localhost:1521:orcl";
//java:oracle:thin: 表示使用的是thin驱动
//@srv:1521: 表示使用的服务器的名字和端口号
//dbname: 表示数据库的SID
lConn = DriverManager.getConnection(lUrl,"system","rg");
lStat = lConn.createStatement();
//创建表
String createTableCoffees = "CREATE TABLE COFFEES " +
"(COF_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, " +
"SALES INTEGER, TOTAL INTEGER)";
lStat.executeUpdate(createTableCoffees);
//插入数据
lStat.executeUpdate("INSERT INTO COFFEES VALUES ('Colombian', 101, 7.99, 0, 0)");
lStat.executeUpdate("INSERT INTO COFFEES VALUES ('Espresso', 150, 9.99, 0, 0)");
lStat.executeUpdate("INSERT INTO COFFEES VALUES ('Colombian_Decaf', 101, 8.99, 0, 0)");
lStat.executeUpdate("INSERT INTO COFFEES VALUES ('French_Roast_Decaf', 49, 9.99, 0, 0)");
//查询结果
lRs = lStat.executeQuery("select * from COFFEES");
//显示结果
out.println("

");

while (lRs.next()) {
out.print("
" + lRs.getString(1));
//COF_NAME
out.print( "
" + lRs.getInt(2));
//SUP_ID
out.print( "
" + lRs.getFloat(3));
//PRICE
out.print( "
" + lRs.getInt(4));
//SALES
out.println( "
" + lRs.getInt(5));
//TOTAL
}
out.println("
");
lRs.close();
lStat.close();
} catch (SQLException e) {
throw new ServletException(e);
} finally {
try {
if (lConn != null)
lConn.close();
} catch (SQLException e) {
}
}
%>