Search code examples
javadatabasederby

I can't connect to a database - program doesn't know where JAR file is


I am trying to copy an example from chapter 23 of Cay S. Horstmann's Big Java, which you can find online as a PDF file just in case if you need it as a reference: http://bcs.wiley.com/he-bcs/Books?action=chapter&bcsId=7872&itemId=1118431111&chapterId=87075

My program is supposed to connect to an Apache Derby database using the java utility tool in a shell window, but it doesn't work. What am I supposed to be entering into the shell window to fix this problem?

My folder structure looks like this in IntelliJ:

My IntelliJ folder structure

This is the code:

package Chapter23RelationalDatabases.database;

import java.io.*;
import java.sql.*;

public class TestDB {
    public static void main(String[] args) throws Exception {
        if (args.length == 0) {
            System.out.println(
                    "Usage: java -classpath driver_class_path"
                    + File.pathSeparator
                    + ". TestDB propertiesFile");
            return;
        }

        SimpleDataSource.init(args[0]);

        Connection conn = SimpleDataSource.getConnection();
        try {
            Statement stat = conn.createStatement();

            stat.execute("CREATE TABLE Test (Name VARCHAR(20))");
            stat.execute("INSERT INTO Test VALUES ('Romeo')");

            ResultSet result = stat.executeQuery("SELECT * FROM Test");
            result.next();
            System.out.println(result.getString("Name"));

            stat.execute("DROP TABLE Test");
        } finally {
            conn.close();
        }
    }
}

package Chapter23RelationalDatabases.database;

import java.io.*;
import java.sql.*;
import java.util.Properties;

public class SimpleDataSource {
    private static String url;
    private static String username;
    private static String password;

    /**
     * Initializes the data source.
     * @param fileName the name of the property file that contains
     *                 the database driver, URL, username, and password
     */
    public static void init(String fileName) throws IOException, ClassNotFoundException {
        Properties props = new Properties();
        FileInputStream in = new FileInputStream(fileName);
        props.load(in);

        String driver = props.getProperty("jdbc.driver");
        url = props.getProperty("jdbc.url");
        username = props.getProperty("jdbc.username");
        if (username == null)
            username = "";
        password = props.getProperty("jdbc.password");
        if (password == null)
            password = "";
        if (driver != null)
            Class.forName(driver);
    }

    /**
     * Gets a connection to the database.
     * @return the database connection
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }
}

This is the contents of the database.properties file:

jdbc.url=jdbc:derby:BigJavaDB;create=true

This is the error stack when I try to run my program:

 Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:derby:BigJavaDB;create=true
 at java.sql.DriverManager.getConnection(DriverManager.java:689)
 at java.sql.DriverManager.getConnection(DriverManager.java:247)
 at Chapter23RelationalDatabases.database.SimpleDataSource.getConnection(SimpleDataSource.java:42)
 at Chapter23RelationalDatabases.database.TestDB.main(TestDB.java:20)

Solution

  • Why would you enter in anything into the "Shell Window" when you are using IntelliJ? you need to add derby jars to your class path, if you use maven you can simply add this:

        <!-- APACHE DERBY - for an embedded database -->
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derby</artifactId>
            <version>10.10.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derbyclient</artifactId>
            <version>10.10.1.1</version>
        </dependency>
    
        <!-- MYSQL Connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.28</version>
        </dependency>
    

    Otherwise you can search for these yourself here http://mvnrepository.com/artifact/org.apache.derby/derby download the jars and add them to your class path manually which is what most beginners do. You can add jars to the classpath on the command line with the -cp flag but only use the command line with java to learn basic programming concepts. Other wise use a build tool like maven. I think you should maybe checkout some tutorial videos with adding jars to the classpath with IntelliJ/Eclipse/Netbeans. Then learn how to use maven, which I highly recommend as a beginner.