No suitable driver found Postgres JDBC

I get a "no suitable driver" error when I test my web service on tomcat. I have JDBC.jar in the lib folder, as various tutorials say. Here is my code:

public class PostDBConnection { PreparedStatement st; ResultSet rs; Connection con; DataSource ds; InitialContext cxt; String url = "jdbc:postgresql://127.0.0.1:5432/UptonDB"; String user = "*****"; String password = "*******"; String query = ""; StringBuilder response = new StringBuilder(); @SuppressWarnings("unused") public String getInfo(){ int size = 0; try { cxt = new InitialContext(); ds = (DataSource) cxt.lookup("java:comp/env/jdbc/UptonDB"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } try{ try { Class.forName("org.postgres.Driver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } con = DriverManager.getConnection(url, user, password); st = con.prepareStatement("SELECT VERSION()"); rs = st.executeQuery(); while(rs.next()) { response.append(rs.getString(1)); } } catch(SQLException exc) { Logger lgr = Logger.getLogger(PostDBConnection.class.getName()); lgr.log(Level.SEVERE, exc.getMessage(), exc); } finally { try { if (rs != null) { rs.close(); } if (st != null) { st.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(PostDBConnection.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } } return response.toString(); } 

Also included are the web.xml and context.xml files created on the following Tomcat websites:

  <resource-ref> <description>PostgreSQL Data Source </description> <res-ref-name>jdbc/UptonDB</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> 

web.xml:

  <?xml version="1.0" encoding="UTF-8"?> <Context> <Resource name="jdbc/UptonDB" auth="Container" type="javax.sql.DataSource" removeAbandoned="true" removeAbandonedTimeout="30" maxActive="80" maxIdle="30" maxWait="10000" username="*****" password="*******" driverClassName="org.postgresql.Driver" url = "jdbc:postgresql://127.0.0.1:5432/UptonDB" useUnicode="true" characterEncoding="utf-8" characterSetResults="utf8"/> </Context> 

Any help is appreciated!

+4
source share
1 answer

The correct driver name is org.postgresql.Driver , not org.postgres.Driver

Update:

Check out this page, let it learn a little, and you should be fine :) http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html

Instead of using DriverManager, you should just search (you already did this) and get a connection to the DataSource (you can remove pwd, user and other unused things from your code):

 Context initContext = new InitialContext(); Context envContext = (Context)initContext.lookup("java:/comp/env"); DataSource ds = (DataSource)envContext.lookup("jdbc/UptonDB"); Connection conn = ds.getConnection(); 
+6
source

All Articles