问题
I'm trying to compile this small piece of code, to help me connect to my db and retrieve some information to test it. I am using Netbeans on a Windows 7 x64 machine. This is the code:
package passwordprotector;
import java.sql.*;
public class PasswordProtector {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String host = "jdbc:derby://localhost:1527/PasswordProtector DB";
String dbUsername = "john";
String dbPassword = "arsenal";
/*try{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
}catch(ClassNotFoundException e){
System.out.println(e);
}*/
try{
Connection con = DriverManager.getConnection(host, dbUsername, dbPassword);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM APP.PERSON");
while (rs.next()) {
String uName = rs.getString("uname");
String uPass = rs.getString("upass");
System.out.println("Username: " + uName + "/n" + "Password: " + uPass);
}
}catch(SQLException e){
System.err.println(e);
}
}
}
When I compile and run I receive this error:
java.sql.SQLException: No suitable driver found for jdbc:derby://localhost:1527/PasswordProtector DB
BUILD SUCCESSFUL (total time: 0 seconds)
When I right click on my db and select properties I can see it's location, like so:
Database URL: jdbc:derby://localhost:1527/PasswordProtector
I've checked with others who have posted about this and it seems they had an incorrect URL as the issue, but I can't see any other URL which I can use apart from the one posted.
I've tried with and without the ending ' DB' for the String host, neither works.
I've also already read from here and still couldn't figure out why the URl is incorrect:
回答1:
Not sure the problem with the database URL connection, but in the usage of the correct driver. If the database is embedded you should use the driver commented in your post and example from my answer, there's also tutorial embedded derby.
if not then use
Class.forName("org.apache.derby.jdbc.ClientDriver");
It's a different driver to connect to the database running standalone. In this case see derby network client documentation how to configure and run derby network client.
回答2:
Make sure derbyrun.jar is in your classpath. It resides in the db/lib directory of your JDK.
回答3:
Doing a quick search on Maven and Derby, included the following in my pom:
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.10.2.0</version>
</dependency>
and everything worked afterwards, so it may be a library reference issue if the previous solution did not work.
来源:https://stackoverflow.com/questions/14547109/java-sql-error-no-suitable-driver-found