Exception in thread “main” java.lang.ClassNotFoundException: org.h2.Driver

164
10 декабря 2019, 17:50

я новичок в Java, мне в универе надо сделать приложение, связаное с бд. я на одном сайте нашел код, скопировал его, но он не заработал (выдал мне Exception in thread "main" java.lang.ClassNotFoundException: org.h2.Driver). Помогите решить проблему.

public class SqlExamples {
public static void init() throws ClassNotFoundException {
    Class.forName("org.h2.Driver");
}
public static Connection getConnection() throws SQLException {
    return DriverManager.getConnection("jdbc:h2:mem:test");
}
public static void statementsOld() {
    Connection connection = null;
    Statement statement = null;
    try {
        connection = getConnection();
        statement = connection.createStatement();
        statement.execute("create table user(" +
                "id integer primary key auto_increment, " +
                "name varchar(100));");
        statement.execute("insert into user(name) values('borya'),('petya')");
        ResultSet rs = statement.executeQuery("select * from user");
        while (rs.next()) {
            System.out.println(rs.getInt("id") + " : " + rs.getString("name"));
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        if (statement != null)
            try { statement.close(); }
            catch (SQLException ignore) { }
        if (connection != null)
            try { connection.close(); }
            catch (SQLException ignore) { }
    }
}
public static void statements(Connection connection) throws SQLException {
    try (Statement statement = connection.createStatement()) {
        statement.execute("create table user(" +
                "id integer primary key auto_increment, " +
                "name varchar(100));");
        statement.execute("insert into user(name) values('borya'),('petya')");
    }
}
public static void resultSet(Connection connection) throws SQLException {
    try (Statement statement = connection.createStatement()) {
        ResultSet rs = statement.executeQuery("select * from user");
        while (rs.next()) {
            System.out.println(rs.getInt("id") + " : " + rs.getString("name"));
        }
        System.out.println("----------------");
    }
}
public static void prepare(Connection connection) throws SQLException {
    try (PreparedStatement statement = connection
            .prepareStatement("insert into user(id,name) values(?,?)")) {
        statement.setInt(1, 3);
        statement.setString(2, "fedya");
        statement.executeUpdate();
        statement.setInt(1, 4);
        statement.setString(2, "misha");
        statement.addBatch();
        statement.setInt(1, 5);
        statement.setString(2, "grisha");
        statement.addBatch();
        statement.executeBatch();
    }
}
public static void transactions(Connection connection) throws SQLException {
    try (Statement statement = connection.createStatement()) {
        connection.setAutoCommit(false);
        try {
            statement.execute("insert into user(name) values('kesha')");
            connection.commit();
        } catch (SQLException e)  {
            connection.rollback();
        }
        connection.setAutoCommit(true);
    }
}
public static void main(String[] args) throws Exception {
    init();
    try (Connection connection = getConnection()) {
        statements(connection);
        resultSet(connection);
        prepare(connection);
        resultSet(connection);
        transactions(connection);
        resultSet(connection);
    }
}

}

Answer 1

Скорее всего вы не подключили H2 JDBC драйвер к проекту. Если вы используете Maven, то добавьте зависимость в pom.xml

<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.199</version>
    <scope>test</scope>
</dependency>

Либо скачайте JAR'ник https://mvnrepository.com/artifact/com.h2database/h2/1.4.199 и подключите его к проекту вручную.

READ ALSO
selenium (multilogin) - finished with exit code 1

selenium (multilogin) - finished with exit code 1

в рамках работы нужно привязать тесты, к multiloginИспользую код предоставленный на их странице, в теории он должен запустить бразуер мультилогина...

160
Список из изображений в android

Список из изображений в android

Возможно ли из этого вместо текстового списка, сделать список из изображений?

202
RecyclerView onClickListener

RecyclerView onClickListener

Можно ли в RecyclerView прослушать нажатия и как это сделать , если образец layout повторяется несколько раз

240
Добавление приложение в избранное Huawei Xioami

Добавление приложение в избранное Huawei Xioami

Можно ли на Huawei и Xioami программно добавить приложение в избранное?

192