0

I've successfully connected to the database through intellij, but I can't figure out how to run sql statements in the main. I have a database class that can run all of the SQL statements but can't get it to work as if I were to write functions that can insert and delete.

public static void main (String[] args)
    {

        Connection conn;

        {
            try {
                conn = DriverManager.getConnection("jdbc:mysql://35.247.87.196:4406","username","password");
                Statement stmt=conn.createStatement();
                String strselect="select * from EmployeeTable";
                System.out.println("The sql statement is: "+strselect+"\n");

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

and I get the exception

java.sql.SQLException: No suitable driver found for jdbc:mysql://35.247.87.196:3306
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
    at DataGenerator.main(DataGenerator.java:30)
  • You should get the jar file in the classpath. If you are using a proper IDE (eclipse etc), you can include jar file in build-path. Anyway, you may need class.forName("...") hack unless you are using a framework like Springboot. – Edward Aung Apr 15 '19 at 00:35
  • Search Stack Overflow before posting. For example: [`No suitable driver found for jdbc`](https://stackoverflow.com/search?q=No+suitable+driver+found+for+jdbc) shows 450 hits. – Basil Bourque Apr 15 '19 at 06:10

1 Answers1

-1

Out of the box, java doesn't support any databases. You need to plug in drivers for database engines in order to make it work.

How do you do that? Just make sure the 'JDBC driver' is on the classpath. There is no need to do anything but that. So, find the JDBC driver for your db engine and ensure that that jar is on your classpath when you run this.

As a side note, to help you debug things in the future: Exceptions have at least 4 interesting bits of info in them (the type, the message, the trace, and the causal chain). Printing all that is hard, so don't try. Either [A] handle the exception (and printing it or logging it is NOT handling it!) or just throw it onwards. your main method should generally have throws Exception tacked on. It also saves a huge amount of written code (no need for a bunch of try/catch blocks with a crappy 'print the error' code in the catch block!

So, definitely, delete the try, the catch, the print, and add 'throws Exception' to your method instead.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72