What is import com.mysql.jdbc.Driver;

2019-05-29 00:08发布

问题:

As part of my project I am trying to connect it with database. I searched in google for the code and I got the following code. In that I don't understand 2 things - "import com.mysql.jdbc.Driver;" and "new Driver". What do these 2 mean ?

package javasql;

import com.mysql.jdbc.Driver;
import java.sql.*;

public class Connect {
public Connect() throws SQLException{
    makeConnection();
} 

private Connection koneksi;  

 public  Connection makeConnection() throws SQLException {
    if (koneksi == null) {
         new Driver();
        // buat koneksi
         koneksi = DriverManager.getConnection(
                   "jdbc:mysql://localhost:3306/mysql","root","virus");
     }
     return koneksi;
 }  

 public static void main(String args[]) {
     try {
         Connect c = new Connect();
         System.out.println("Connection established");
     }
     catch (SQLException e) {
         e.printStackTrace();
         System.err.println("Connection Failure");
     }  

}
}

package javasql;

import java.sql.*;

public class SqlStatement {
private Statement statement;
public SqlStatement() throws SQLException{
    makeStatement();
}
public Statement makeStatement() throws SQLException{
    Connect c = new Connect();
    Connection conn = c.makeConnection();
    statement = conn.createStatement();
    return statement;
}
public void insert(String name,int npm)throws SQLException{
    statement.execute("insert into Student values(\""+name+"\","+npm+");");
}
public static void main(String arg[]){
    try {
        SqlStatement s = new SqlStatement();
        s.insert("Ferdi2",3);
        s.insert("Anca2",3);
        System.out.println("Success");
    }
    catch(SQLException e){
        System.out.println("Failed");
        e.printStackTrace();
    }
}
}

I use NetBeans IDE to develop my project. When I used these codes I made it as a new project. Then it worked fine. But whenever I tried to include these codes in another projects errors are showing at "import com.mysql.jdbc.Driver;". Why is it so ? Can I use these 2 codes in another projects ?

回答1:

The driver serves as an interface between your application and the database.

Are you using MySQL? If so, you can find the MySQl Java drivers here.



回答2:

All you need is

// This will load the MySQL driver, each DB has its own driver Class.forName("com.mysql.jdbc.Driver")

This acts like class loader and load your driver class for you. For that you need to add the corresponding jar file.



回答3:

Using import com.mysql.jdbc.Driver; in JDBC code is not a good practice and you need to import only java.sql.* and javax.sql.*. The reason is to detach the code from the specific driver implementation.

See here for more information how to make JDBC connections. And DriverManager.getConnection(...) is enough to get connection.



标签: java jdbc