简体   繁体   中英

Connecting fo MySql from JDBC in java

I have a program written in java. This program when run from dos prompt raises driver class not found

 import java.sql.*;
 public class SimpleDb {
 public static void main(String[] args)throws SQLException,ClassNotFoundException 
 {

    Class.forName("com.mysql.jdbc.Driver");    

   Connection con = DriverManager.get connection("jdbc:mysql://host/db");  

   Statement sta = con.create statement();

    ResultSet rs = sta.executeQuery(query);


   con.close();

  }

}

Help please

You need to add the MySQL Connector to your project: http://dev.mysql.com/downloads/connector/j/

Also Class.forName is not needed anymore, and you should use proper exception handling and resource managment using try-with-resources:

try (Connection conn = DriverManager.getConnection("...") {
    PreparedStatement ps = conn.prepareStatement("...");
    try (ResultSet rs = ps.executeQuery()) {
        /* Parse result */
    }
} catch (SQLException ex) {
    for (Throwable t : ex) {
        t.printStackTrace();
    }
}

There are several things wrong with your code, first make sure you have mysql-connector-java-5.0.8-bin.jar in your library. Once you add that to the library you will get a another problem which is you don't have your sql username or password Here is the correct way to do it:

 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;

 Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {

        Class.forName("com.mysql.jdbc.Driver").newInstance();
        String connectionUrl = "jdbc:mysql://localhost:3306/db1";
        String connectionUser = "root";
        String connectionPassword = "password";
        conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
        stmt = conn.createStatement();
        rs = stmt.executeQuery("SELECT * FROM Laptop Where Owners = 'John'");
        while (rs.next()) {
            String Owners = rs.getString("Owners");
            String model = rs.getString("Model");
            String Manufacturer = rs.getString("Manufacturer");
            int Screen = rs.getInt("Screen");
            int Years = rs.getInt("Years");
            System.out.println(Owners + " " + model + " " + Manufacturer + " " + Screen + " " +Years);
        }
    } catch (Exception e) {
        e.printStackTrace();

com.mysql.jdbc.Driver is a class in mysqljdbc.jar Although java 6 supports automatic driver discovery to be safe load the driver explicitly. Kindly specify the appropriate driver in the class path as shown in the dos prompt

  java -cp .;lib/mysqljdbc.jar SimpleDb

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