我正在创建简单的HelloWorld Web应用程序。我想使用本地derby db。
我的pom:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.14.1.0</version>
<scope>test</scope>
</dependency>
和连接服务类MyDB,我只想从表中获取文本并显示:
public void connecToDerby() throws SQLException{
String dbUrl = "jdbc:derby:D:\\Projects\\JavaWebApplication\\FirstMavenProject; create=true";
conn = DriverManager.getConnection(dbUrl);
}
public void initDb() throws SQLException {
Statement statement = conn.createStatement();
statement.executeUpdate("Create table welcometext(id int primary key, text varchar(100))");
statement.executeUpdate("INSERT into welcometext values (1, 'Hello Java World')");
statement.close();
}
但我有例外:
java.sql.SQLException: No suitable driver found for jdbc:derby:D:\Projects\JavaWebApplication\FirstMavenProject; create=true
如何解决?使用本地德比是否正确?我正在研究Intelij IDEA。
答案 0 :(得分:0)
似乎您没有加载驱动程序类。请根据需要使用以下选项之一
Class.forName("org.apache.derby.jdbc.ClientDriver");
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
在从DriverManager
获得连接之前。
答案 1 :(得分:0)
我的代码在这里,有效。也许你输了Class.forName(JDBC_DRIVER_NAME);
private static final String JDBC_DRIVER_NAME = "org.apache.derby.jdbc.EmbeddedDriver";
private static final String NACOS_HOME = "D:\\nacos";
private static final String DERBY_BASE_DIR = "data" + File.separator + "derby-data";
private static final String USER_NAME = "nacos";
private static final String PASSWORD = "nacos";
static Connection conn = null;
public static Connection getConnection() {
if (conn==null){
try {
Class.forName(JDBC_DRIVER_NAME);
String url = "jdbc:derby:" + NACOS_HOME + File.separator + DERBY_BASE_DIR + ";create=true";
conn = DriverManager.getConnection(url, USER_NAME, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
return conn;
}