数据库连接池异常 NoInitialContextException
数据库连接池异常NoInitialContextException
项目名和数据库名是 myhb ,用户名和密码是:root
1 Tomcat 根目录下conf/context.xml
<Resource name="jdbc/myhb" anth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="300" maxWait="10000"
username="root" password="root"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver://localhost:1433;databasename=myhb"
></Resource>
2 项目下的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" .......
<resource-ref>
<description>myhb DataSource</description>
<res-ref-name>jdbc/myhb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
3 Tomcat的lib下添加了sqljdbc.jar
4 类
public class ConnectionManager {
Connection con=null;
public Connection getConn(){
try {
Context ct=new InitialContext();
DataSource ds=(DataSource)ct.lookup("java:comp/env/jdbc/myhb"); //报错行
con=ds.getConnection();
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
}
public class ProductsDao extends BaseJdbcDao{
ConnectionManager cm=new ConnectionManager();
public Product get(int id)
{
Product p=null;
try {
String sql="select * from Product where id=?";
con=cm.getConn();
ps=con.prepareStatement(sql);
ps.setInt(0,id);
rs=ps.executeQuery();
while(rs.next())
{
p=new Product();
p.setId(rs.getInt(1));
p.setImage(rs.getString(2));
p.setIntroduce(rs.getString(3));
p.setName(rs.getString(4));
p.setPrice(rs.getDouble(5));
}
} catch (SQLException e) {
e.printStackTrace();
}
return p;
}
}
Main:
ProductsDao pd=new ProductsDao();
System.out.println(pd.get(1).getName());
运行后错误信息:
javax.naming.NoInitialContextException: Need to specify class name in environment or
system property, or as an applet parameter, or in an application resource file:
java.naming.factory.initial