我想从Cay S. Horstmann的Big Java的第23章中复制一个示例,您可以在网上以PDF格式在线查找情况下,如果你需要它作为参考:http://bcs.wiley.com/he-bcs/Books?action=chapter&bcsId=7872&itemId=1118431111&chapterId=87075我无法连接到数据库 - 程序不知道JAR文件的位置
我的程序应该连接到一个Apache Derby数据库使用外壳窗口中的java
实用工具,但它不起作用。我应该怎样进入shell窗口来解决这个问题?
我的文件夹结构看起来像这样的IntelliJ:
这是代码:
package Chapter23RelationalDatabases.database;
import java.io.*;
import java.sql.*;
public class TestDB {
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.out.println(
"Usage: java -classpath driver_class_path"
+ File.pathSeparator
+ ". TestDB propertiesFile");
return;
}
SimpleDataSource.init(args[0]);
Connection conn = SimpleDataSource.getConnection();
try {
Statement stat = conn.createStatement();
stat.execute("CREATE TABLE Test (Name VARCHAR(20))");
stat.execute("INSERT INTO Test VALUES ('Romeo')");
ResultSet result = stat.executeQuery("SELECT * FROM Test");
result.next();
System.out.println(result.getString("Name"));
stat.execute("DROP TABLE Test");
} finally {
conn.close();
}
}
}
package Chapter23RelationalDatabases.database;
import java.io.*;
import java.sql.*;
import java.util.Properties;
public class SimpleDataSource {
private static String url;
private static String username;
private static String password;
/**
* Initializes the data source.
* @param fileName the name of the property file that contains
* the database driver, URL, username, and password
*/
public static void init(String fileName) throws IOException, ClassNotFoundException {
Properties props = new Properties();
FileInputStream in = new FileInputStream(fileName);
props.load(in);
String driver = props.getProperty("jdbc.driver");
url = props.getProperty("jdbc.url");
username = props.getProperty("jdbc.username");
if (username == null)
username = "";
password = props.getProperty("jdbc.password");
if (password == null)
password = "";
if (driver != null)
Class.forName(driver);
}
/**
* Gets a connection to the database.
* @return the database connection
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
}
这是内容文件:
jdbc.url=jdbc:derby:BigJavaDB;create=true
这是错误堆栈,当我尝试运行我的程序:
Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:derby:BigJavaDB;create=true
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at Chapter23RelationalDatabases.database.SimpleDataSource.getConnection(SimpleDataSource.java:42)
at Chapter23RelationalDatabases.database.TestDB.main(TestDB.java:20)
你看过其他问题的答案吗? http://stackoverflow.com/questions/22384710/java-sql-sqlexception-no-suitable-driver-found-for-jdbcmysql-localhost3306 http://stackoverflow.com/questions/1911253/the-infamous-no- tomcat-5-5-postgres-and-jdbc – NuclearPeon
请确保在您的计算机上指定了jar的路径,或者将jar复制到当前的JRE bin文件夹(其他files.jar所在的文件夹) – MaxZoom
具体来说,您需要的jar是Apache Derby下载的derby.jar或JDK发行版中的JavaDB。 –