JSP连接数据库
最近学习JSP,有一个程序调试不过去,总是在“ pstmt=this.dbc.getConnection().prepareStatement(sql);”处出错,如图,pstmt值为“null”,用的是myeclipse8.6,tomcat7.0,jdk6,JSP插入页面调用时,出现以上的错误,当NEW ConnectJDBC.java时,调用其方法getConnection方法不能返回数据库连接;当用JAVA编文件调用时,就不出错了;请高手指点迷津,谢谢!
userDAOProxy.java
package mws.user.dao.proxy;
import java.util.List;
import mws.ConnectJDBC.ConnectJDBC;
import mws.user.dao.IUserDAO;
import mws.user.dao.impl.UserDAOImpl;
import mws.user.vo.User;
public class UserDAOProxy implements IUserDAO {
private ConnectJDBC dbc=null;
private UserDAOImpl userdao=null;
public UserDAOProxy() {
dbc=new ConnectJDBC();
userdao=new UserDAOImpl(dbc);
}
public boolean doCreate(User user) throws Exception {
// TODO Auto-generated method stub
boolean flag=false;
try {
flag=this.userdao.doCreate(user);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
this.dbc.Close();
}
return flag;
}
}
userDAOImpl.java
package mws.user.dao.impl;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import mws.ConnectJDBC.ConnectJDBC;
import mws.user.dao.IUserDAO;
import mws.user.vo.User;
public class UserDAOImpl implements IUserDAO{
private ConnectJDBC dbc=null;
public UserDAOImpl(ConnectJDBC dbcon) {
this.dbc=dbcon;
}
public boolean doCreate(User user) throws Exception {
// TODO Auto-generated method stub15839710664
String sql= "insert into userlogin values (userseq.nextval,?,?)";
PreparedStatement pstmt=null;
System.out.println(user.getUsername());
System.out.println(user.getPaword());
System.out.println(this.dbc.getConnection());
pstmt=this.dbc.getConnection().prepareStatement(sql);
pstmt.setString(1,user.getUsername());
pstmt.setString(2,user.getPaword());
if(pstmt.executeUpdate()>0){
return true;
}
return false;
}
}
ConnectJDBC.java
package mws.ConnectJDBC;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectJDBC {
public static final String DBDRIVER= "oracle.jdbc.driver.OracleDriver";
public static final String DBURL= "jdbc:oracle:thin:@localhost:1521:mws";
public static final String DBUSER= "scott";
public static final String DBPASS= "tiger";
private Connection conn=null;
public ConnectJDBC() {
super();
}
public Connection getConnection(){
try {
if(conn==null||conn.isClosed()){
Class.forName(DBDRIVER); Conn=DriverManager.getConnection(DBURL,DBUSER,DBPASS);
}catch (Exception e) {
// TODO: handle exception
}
return conn;
}
public void Close(){
try {
if(conn!=null&&!conn.isClosed()){
conn.close();
System.out.println("连接关闭成功");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
新建 Microsoft Word 文档.zip
(131.39 KB)