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("
"+"Empno"+" | ");"+"Ename"+" | ");"+"Job"+" | ");"+"Mgr"+" | ");"+"hiredate"+" | ");"+"Sal"+" | ");"+"Comm"+" | ");"+"Deptno"+" |
"+rs.getString(1)+" | ");"+rs.getString(2)+" | ");"+rs.getString(3)+" | ");"+rs.getString(4)+" | ");"+rs.getString(5)+" | ");"+rs.getString(6)+" | ");"+rs.getString(7)+" | ");"+rs.getString(8)+" |
辅助类:
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 的,你改一下驱动!
配置数据源,使用jdbc连