conn=ds.getConnection();为什么conn会为空呢?请大家帮忙!
我在struts-config.xml中配置了数据源:
<data-source type= "oracle.jdbc.pool.OracleDataSource ">
<set-property property= "driverClassName "
value= "oracle.jdbc.driver.OracleDriver " />
<set-property property= "url "
value= "jdbc:oracle:thin:@192.168.0.204:1521:yiyao " />
<set-property property= "username "
value= "cra " />
<set-property property= "password "
value= "medlink " />
<set-property property= "maxActive "
value= "10 " />
<set-property property= "maxWait "
value= "5000 " />
<set-property property= "defaultAutoCommit "
value= "false " />
<set-property property= "defaultReadOnly "
value= "false " />
</data-source>
然后在登录的action中写下面的代码:
DataSource ds=null;
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try{
try{
System.out.println( "进入try ");
ds=getDataSource(request);
conn=ds.getConnection();
if (conn!=null){
System.out.println( "取得连接 ");}
else {System.out.println( "连接为空 ");}
strsql= "select * from centerUser where username=? and password=? ";
pstmt=conn.prepareStatement(strsql);
pstmt.setString(1, username);
pstmt.setString(2, password);
System.out.println( "sql语句完成 ");
rs=pstmt.executeQuery();
System.out.println( "查询执行完成 ");
rs.first();
if (rs.next()) {
System.out.println(rs.getString( "truename "));
}else{
System.out.println( "fail ");
}
}catch (Exception e) {
if (rs==null){
System.out.println( "rs为空 ");}
else{
System.out.println( "rs不为空 ");
}
if (conn==null){
System.out.println( "连接为空 ");}
else{
System.out.println( "连接不为空 ");
}
if (ds==null){
System.out.println( "数据源为空 ");}
else{
System.out.println( "数据源不为空 ");
}
}
}finally{
try{
if (rs!=null){
rs.close();}
if (pstmt!=null){
pstmt.close();}
if (conn!=null){
conn.close();}
}catch (Exception e){
}
}
得到的结果是:
进入try
rs为空
连接为空
数据源不为空
[解决办法]
ds=getDataSource(request);
conn=ds.getConnection(); 有问题;
给你段实例,希望能有所帮助。
public static Connection getConnection(){
Connection c = null;
try{
Class.forName( "oracle.jdbc.driver.OracleDriver ");
c = DriverManager.getConnection( "jdbc:oracle:thin:@32.36.3.180:1521:ora9i ", "photo ", "photo ");
}
catch(java.lang.ClassNotFoundException e)
{
System.out.println( "myconn(): "+e.getMessage());
}
catch(java.sql.SQLException e)
{
System.out.println( "conn(): "+e.getMessage());
}
catch(Exception e)
{
System.out.println( "Driver error! ");
System.err.println(e.getMessage());
}
return c;
}
}
[解决办法]
ds=getDataSource(request);不知道你这个方法怎么写的
一般将数据库连接池在web容器中配置,然后通过Context接口来得到这个jndi数据源
[解决办法]
struts-config.xml在这里面配置数据源 我没做过
[解决办法]
另一种可能,你先前调用的程序,conn没有close