什么是导入com.mysql.jdbc.Driver;

作为我项目的一部分,我正在尝试将其与数据库连接。 我在谷歌搜索代码,我得到以下代码。 在那里我不明白两件事 – “import com.mysql.jdbc.Driver;” 和“新司机”。 这两个意味着什么?

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(); } } } 

我使用NetBeans IDE开发我的项目。 当我使用这些代码时,我将其作为一个新项目。 然后它工作正常。 但每当我试图将这些代码包含在另一个项目中时,错误就会出现在“import com.mysql.jdbc.Driver;”中。 为什么会这样? 我可以在其他项目中使用这两个代码吗?

驱动程序充当应用程序和数据库之间的接口。

你在使用MySQL吗? 如果是这样,您可以在此处找到MySQl Java驱动程序。

所有你需要的是

//这将加载MySQL驱动程序,每个DB都有自己的驱动程序Class.forName("com.mysql.jdbc.Driver")

这类似于类加载器并为您加载驱动程序类。 为此,您需要添加相应的jar文件。

使用import com.mysql.jdbc.Driver;JDBC代码中不是一个好习惯,你只需要导入java.sql.*javax.sql.* 。 原因是从特定的驱动程序实现中分离代码。

有关如何建立JDBC连接的更多信息,请参见此处 。 并且DriverManager.getConnection(...)足以获得连接。