【发布时间】:2013-04-13 00:03:54
【问题描述】:
我正在尝试使用 JDBC 连接到我的本地主机上的 Derby 数据库。
我已经使用命令java -jar lib;derbyrun.jar server start启动了数据库,在1527端口成功启动。
在另一个命令终端上,我使用命令:java -classpath .;lib;derbyclient.jar testsqldatabase.TestSQLDatabase,但出现以下错误:
java.sql.SQLException: No suitable driver found for jdbc:postgresql:COREJAVA
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at testsqldatabase.TestSQLDatabase.getConnection(TestSQLDatabase.jav
)
at testsqldatabase.TestSQLDatabase.runTest(TestSQLDatabase.java:39)
at testsqldatabase.TestSQLDatabase.main(TestSQLDatabase.java:26)
我的 datatbase.properties 文件包含以下几行:
jdbc.drivers=org.postgresql.Driver
jdbc.url=jdbc:postgresql:COREJAVA
jdbc.username=dbuser
jdbc.password=secret
java程序如下:
public class TestSQLDatabase
{
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
try
{
runTest();
}
catch(SQLException ex)
{
for(Throwable t: ex)
t.printStackTrace();
}
}
/*Runs a test by creating a table, adding a value,
showing the table contents, removing the table*/
public static void runTest() throws SQLException, IOException
{
try(Connection conn = getConnection())
{
Statement stat = conn.createStatement();
stat.executeUpdate("CTEATE TABLE Greetings (Message CHAR(20))");
stat.executeUpdate("INSERT INTO Greetings VALUES ('Hello, World!')");
try(ResultSet result = stat.executeQuery("SELECT * FROM Greetings"))
{
if(result.next())
System.out.println(result.getString(1));
}
stat.executeUpdate("DROP TABLE Greetings");
}
}
/*
* Gets a connection from the properties specified in the
* file database.properties. @return the database connection
*/
public static Connection getConnection() throws SQLException, IOException
{
Properties props = new Properties();
try(InputStream in = Files.newInputStream(Paths.get("database.properties")))
{
props.load(in);
}
String drivers = props.getProperty("jdbc.drivers");
if(drivers != null) System.setProperty("jdbc.drivers", drivers);
String url = props.getProperty("jdbc.url");
String username = props.getProperty("jdbc.username");
String password = props.getProperty("jdbc.password");
return DriverManager.getConnection(url, username, password);
}
}
谁能弄清楚为什么我会从第二个命令终端收到该错误?
谢谢,非常感谢
【问题讨论】:
-
你想连接PostgreSQL数据库吗?
-
好的,我看看我是如何使用两个不同的数据库的。不,我想连接到 Derby DB。这是否是正确的路径:jdbc.url=jdbc:derby:COREJAVA 的 URL?我正在为 Derby 使用 JDK 7 包。谢谢
-
是的,请检查您的驱动程序类型