Search code examples
javapostgresqljdbcosx-snow-leopard

Trying to use jdbc driver for postgresql but it's not working


I have added the jdbc driver to my classpath as far as I know i.e. I added the following to my .profile

export CLASSPATH=$CLASSPATH:location/to/the/jarfile.jar

When I compile my java program I always get this error

javac v9.java
v9.java:8: <identifier> expected
 Class.forName("org.postgresql.Driver");//load the driver
          ^
v9.java:8: illegal start of type
 Class.forName("org.postgresql.Driver");//load the driver
           ^
2 errors

This is driving me insane, any help would be awesome. I'm using Mac OS X Snow Leopard

The java program is here

import java.sql.*;

public class v9
{
 String dbURL = "jdbc:postgresql:mydb";
 String user = "UserName";
 String password = "pswd";
 C  try
{
Class.forName("org.postgresql.Driver");//load the driver
// Connect to the database
Connection DBconn = DriverManager.getConnection( dbURL, user, password );
}
catch (Exception e)
{
    e.printStackTrace();
}
}

Solution

  • Try this - you need a method somewhere:

    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class V9
    {
        public static final String driver = "org.postgresql.Driver";
        public static final String url = "jdbc:postgresql://localhost:5432/party";
        public static final String username = "pgsuper";
        public static final String password = "pgsuper";
    
        public static void main(String [] args)
        {
            try
            {
                Class.forName(driver);
                Connection conn = DriverManager.getConnection(url, username, password);
                System.out.println(conn.getMetaData().getDatabaseProductName());
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }