Question

I am attempting to make a simple DB desk top application using JavaDB embedded. I am using NetBeans as my IDE which is why I decided to use JavaDB and I have the property ;create=true appended to my DB URL. My issue at this point and after a lot of research is how do correctly create tables on the first load of the program? I am also trying to understand when to apply the creating of the tables. Right now I have a class to create and connect to the DB. Thanks in advance for any guidance!

public class ConnectDB
{
    private static final String DB_URL = "jdbc:derby:javaDB;create=true";
    private static final String DB_UN  = "app";
    private static final String DB_PW  = "root";
    private static final String DB_DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";

    Connection conn = null;

    public static Connection ConnectDB()
    {
        try
        {
            Class.forName(DB_DRIVER).newInstance();
            Connection conn = DriverManager.getConnection(DB_URL, DB_UN, DB_PW);
            JOptionPane.showMessageDialog(null, "Connected!");

            return conn;
        }
        catch (Exception e)
        {
            JOptionPane.showMessageDialog(null, e);
            return null;
        }
    }
}
Was it helpful?

Solution

You just have to get a Statement from your Connection and then you can call the method statement.executeUpdate("some normal SQL code to create tables").

Since you will likely call the code to create the tables a single time in your development process, I would put that in some separate class with a main method to create the tables.

What I do instead is that I create the tables directly in MySQL. But I paste-and-copy the MySQL creation commands in the comments of the relevant Java class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top