作爲我的項目的一部分,我試圖將其與數據庫連接。我在谷歌搜索的代碼,我得到了下面的代碼。在這我不明白2件事 - 「import com.mysql.jdbc.Driver;」和「新驅動程序」。這兩個意思是什麼?什麼是導入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;」中都會顯示錯誤。爲什麼這樣?我可以在其他項目中使用這兩個代碼嗎?
您必須包含一個驅動程序庫才能夠與數據庫管理系統進行交互。 'import com.mysql.jdbc.Driver'是yoyu必須在你的類路徑中使用的mysql驅動程序的類。 http://dev.mysql.com/downloads/connector/j/ – dooxe
您需要在項目中包含MYSQL java庫。 import語句告訴編譯器,你正在使用'com.mysql.jdbc'包中的'Driver'類。 – initramfs
謝謝......當我在NetBeans中添加MySQL JDBC驅動程序時,問題就解決了。 – TomJ