jsp怎样连接Oracle数据库

2024-12-29 12:26:37
推荐回答(3个)
回答1:

jsp连接oracle数据库,主要是通过jdbc技术,首先加载驱动类,然后连接url,输入用户名和密码,打开数据库连接资源,如下代码:

<%@page contentType="text/html;charset=gb2312"%>
<%@page import="java.sql.*"%>





<%
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;


request.setCharacterEncoding("GBK");

try{
Class.forName("oracle.jdbc.driver.OracleDriver");//加载oracle数据库驱动
}
catch(ClassNotFoundException ce){
out.println(ce.getMessage());
}
try{
    String url="jdbc:oracle:thin:@localhost:1521:orcl";//连接oracle数据库的url
    conn=DriverManager.getConnection(url,"scott","tiger");//开始连接
    stmt=conn.prepareStatement("select * from emp");//获取返回的结果集
    
rs=stmt.executeQuery();
out.print("");
out.print(""+"Empno"+"");
out.print(""+"Ename"+"");
out.print(""+"Job"+"");
out.print(""+"Mgr"+"");
out.print(""+"hiredate"+"");
out.print(""+"Sal"+"");
out.print(""+"Comm"+"");
out.print(""+"Deptno"+"");


while(rs.next()){
out.print(""+rs.getString(1)+"");
out.print(""+rs.getString(2)+"");
out.print(""+rs.getString(3)+"");
out.print(""+rs.getString(4)+"");
out.print(""+rs.getString(5)+"");
out.print(""+rs.getString(6)+"");
out.print(""+rs.getString(7)+"");
out.print(""+rs.getString(8)+"");
}

out.print("");
    
rs.close();
stmt.close();
conn.close();

}
catch(Exception e){
System.out.println(e.getMessage());
}

%>

回答2:

辅助类:
package dao;
import java.util.*;
import java.sql.*;
public class BaseDao {
public static final String DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
public static final String URL="jdbc:sqlserver://localhost:1433;DataBaseName=bbsMSG";
public static final String USER="sa";
public static final String PASS="sa";

public Connection connection=null;
public PreparedStatement preparedStatement=null;
public ResultSet resultSet=null;

//获得连接
public void getConnection(){
try {
Class.forName(DRIVER);//注册驱动
try {

connection=DriverManager.getConnection(URL, USER, PASS);
} catch (SQLException e) {

e.printStackTrace();
}

} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

//关闭连接
public void closeAll(){
try {
if(resultSet!=null){resultSet.close();}
if(preparedStatement!=null){preparedStatement.close();}
if(connection!=null){connection.close();}
} catch (SQLException e) {
e.printStackTrace();
}
}
//执行SQL语句
public int executeSQL(String sql,String[] param){
int result=0;
getConnection();
try {
preparedStatement=connection.prepareStatement(sql);

if(param!=null){

for(int i=0;i
preparedStatement.setString(i+1, param[i]);

}

}
result=preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
closeAll();
}
return result;
}
}
只不过这是链接Sqlserver 的,你改一下驱动!

回答3:

配置数据源,使用jdbc连