简体   繁体   中英

Connection to a sql database questions

I'm trying to connect to my sql database on localhost. With the following code :

try {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
    } catch(ClassNotFoundException e) {
        System.out.println("JdbcOdbcDriver wasn't found");
        e.printStackTrace();
    }


    Connection connection = null;
    try {
      connection = DriverManager.getConnection("jdbc:mysql://localhost/testBase", "root", "");

      Statement statement = connection.createStatement();
      ResultSet res = statement.executeQuery("");

    }
    catch(SQLException e){ System.out.println(e); }     
    finally {
        if(connection != null) {
            try { connection.close(); } catch (SQLException e) { e.printStackTrace(); }
        }
    }

I have 2 questions related to this code :

  1. I am using the sun.jdbc.odbc.JdbcOdbcDriver driver because it seem that it was the only available on my system, however I've read that it's a windows component... Is there a way to make it platform independent (or is it already) ?
  2. The second catch outputs a

    java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/

    Which is quite annoying and I don't seem to be able to find a way to work...

Thanks for your help !

When you generate jar, you can include all its dependencies.
So, you can use any driver you need and include it when you generate jar for the application.

Now you're cross platform.

About the question #2, that's because you don't have the mysqLconnector at lib folder.
You can download it here: http://dev.mysql.com/downloads/connector/j/

Just include it, if you're using IDE, you can look for a option "include jar/folder" and add it, then, try again; if you aren't in a IDE ... you have to set it on classpath .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM