0

I'm trying to run my code so that I can connect to a database and create tables and such although I keep receiving a package does not exist error.

    import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Random;
public class SQL {

    private static long start;
    private static long end;
    // Make sure and use the java.sql imports.
    protected static Connection m_dbConn = null;

    /**
     * Main method to run the program
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception
    {
        new SQL();

        m_dbConn.close();  //closes the connection
        System.out.println("Connection closed.");
    }

    public SQL() throws Exception
    {

        m_dbConn = DriverManager.getConnection(DB_LOCATION, LOGIN_NAME, PASSWORD);

        activateJDBC();  //activates JDBC

           /**
            * To get the meta data for the DB.
            */
        DatabaseMetaData meta = m_dbConn.getMetaData();


            double[] times = new double[20];  //array for the time

            for(int i = 0; i < 20; i++) 
            {
                //starts the timer
                start = System.currentTimeMillis();
                createTable();
                insertValues();

                //ends the timer
                end = System.currentTimeMillis();
                times[i] = end - start;
                System.out.println("Time to complete " + (i+1) + ": " + times[i]);

                //drops the table
                String dropTable = "DROP TABLE TEST_STOFFEY";
                Statement stmt = m_dbConn.createStatement();
                stmt.execute(dropTable);
            }


    }


    /**
     * Creates the table and runs it in the database
     */
    public void createTable()
    {
        String create = "CREATE TABLE IF NOT EXISTS TEST_STOFFEY"
                + "(num1                   INT                 NOT NULL,"
                + "num2                    INT                 NOT NULL,"
                + "ch                      CHAR(10),"
                + "vch                     VARCHAR(30),"
                + "doub                    DOUBLE)";

        try 
        {
            Statement stmt = m_dbConn.createStatement();
            stmt.execute(create);
            System.out.println("Table Created");
        }
        catch(SQLException e)
        {
            e.printStackTrace();
        }
    }


    /**
     * Inserts our random values up to 25000
     */
    public void insertValues()
    {
        int x = 0;
        int y = 0;
        for(int i = 0; i < 25000; i++)
        {
            try {
                PreparedStatement stmt = m_dbConn.prepareStatement("insert into TEST_STOFFEY values(?,?,?,?,?)");
                stmt.setInt(1, x++);
                stmt.setInt(2, y++); 
                stmt.setString(3, randomString(10));
                stmt.setString(4, randomString((int)Math.random() * 30 + 1));
                stmt.setDouble(5, Math.random() * 100 + 1);
                stmt.executeUpdate(); 
            } catch (SQLException sqle) {

                sqle.printStackTrace();
            }
        }
    }


    /**
     * Creates a random string to add into our values for the table
     * @param c
     * @return
     */
    public String randomString(int c)
    {
        int leftLimit = 97; // letter 'a'
        int rightLimit = 122; // letter 'z'
        int length = c;
        Random random = new Random();
        StringBuilder buffer = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int randomLimitedInt = leftLimit + (int) 
              (random.nextFloat() * (rightLimit - leftLimit + 1));
            buffer.append((char) randomLimitedInt);
        }
        String generatedString = buffer.toString();
        return generatedString;
    }


    /**
     * Activate JDBC
     * @return
     */
    public boolean activateJDBC()
    {
        try
        {
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            /**
            * Creates a connection to the database that you can then send commands to.
            */
            System.out.println("Connection successful");
        }
        catch (SQLException sqle)
        {
            sqle.printStackTrace();
            return false;
        }

        return true;
    }

}

I have mysql-connector-java-5.1.29-bin.jar within my build path under Referenced Libraries. I tried moving things around and nothing. What do I need to change to fix the error?

  • You say it's in your build path. But, is it in your runtime path? How exactly are you running it? – The Impaler Mar 27 '20 at 15:43
  • @TheImpaler I'm not sure how to put it in my runtime path and I'm running it on mobaXterm using javac SQL.java because I need to connect to my schools database – Joshua Stoffey Mar 27 '20 at 15:46
  • Now I'm getting "could not find or load main class SQL.java" – Joshua Stoffey Mar 27 '20 at 15:56
  • You have to run your program with `java -cp my-driver.jar SQL`and not with `java -cp my-driver.jar SQL.java` And I hope that credentials you posted in your code are fake, if not remove them please. – Sergej Masljukow Mar 27 '20 at 20:10
  • Your code should **not** call `DriverManager.registerDriver(new com.mysql.jdbc.Driver())`. `DriverManager.registerDriver` should only be called by JDBC driver implementations themselves. Assuming the 5.1.29 driver (which is pretty old) supports automatic driverloading, just having the driver on the classpath would be sufficient to get it load automatically, and otherwise you should use `Class.forName("com.mysql.jdbc.Driver")` to load it. – Mark Rotteveel Mar 28 '20 at 07:33

0 Answers0