Org sqlite jdbc ошибка

I am trying to get Xerial’s Sample class to work in Eclipse with sqlite, but I keep getting the error «ClassNotFoundException: org.sqlite.JDBC»

I downloaded the sqlite-jdbc-3.7.2.jar file from https://bitbucket.org/xerial/sqlite-jdbc/downloads. Copied it into the lib folder under my project «database_test» in eclipse. Then right-clicked on the Project->Properties->Java Build Path->Libraries Tab->Add JARs->Select the jar file. I am trying to execute this code from Xerial found here: https://bitbucket.org/xerial/sqlite-jdbc#markdown-header-usage

// load the sqlite-JDBC driver using the current class loader
Class.forName("org.sqlite.JDBC");

Connection connection = null;
try
{
  // create a database connection
  connection = DriverManager.getConnection("jdbc:sqlite:sample.db");
  Statement statement = connection.createStatement();
  statement.setQueryTimeout(30);  // set timeout to 30 sec.

  statement.executeUpdate("drop table if exists person");
  statement.executeUpdate("create table person (id integer, name string)");
  statement.executeUpdate("insert into person values(1, 'leo')");
  statement.executeUpdate("insert into person values(2, 'yui')");
  ResultSet rs = statement.executeQuery("select * from person");
  while(rs.next())
  {
    // read the result set
    System.out.println("name = " + rs.getString("name"));
    System.out.println("id = " + rs.getInt("id"));
  }
}
catch(SQLException e)
{
  // if the error message is "out of memory", 
  // it probably means no database file is found
  System.err.println(e.getMessage());
}
finally
{
  try
  {
    if(connection != null)
      connection.close();
  }
  catch(SQLException e)
  {
    // connection close failed.
    System.err.println(e);
  }
}

}
}

Every site I have been to has said add the jar file to your build path or class path and I believe I have done that, but nothing has solved the problem. Any help would be appreciated. Thanks.

asked Aug 6, 2013 at 20:34

user2646175's user avatar

8

Thanks to user phew for the help/ideas.

I missed the obvious command line instructions on Xerial’s site for the Sample program. To get the program to run from the command line, I had to copy the JAR file into the same folder as the .CLASS file. Then run the following command:

java -classpath ".:sqlite-jdbc-(VERSION).jar" Sample

Inside the quotation marks are multiple paths, separated thru a colon (:) under Unix and a semicolon (;) under Windows. The dot as one of the paths is important — only naming the JAR file alone is not enough. A full call on Windows would be:

"%JAVA_HOME%\bin\java.exe" -cp "sqlite-jdbc-(VERSION).jar;." Sample

Note the semicolon instead of the colon. The order of the paths do not really matter, and -cp does the same as -classpath, just shorter.

AmigoJack's user avatar

AmigoJack

5,2441 gold badge15 silver badges31 bronze badges

answered Aug 9, 2013 at 15:26

user2646175's user avatar

user2646175user2646175

2411 gold badge2 silver badges7 bronze badges

1

you can add it by converting your project to maven and the dependency(from https://mvnrepository.com) to your pom.xml as:

</dependency>
    <!-- https://mvnrepository.com/artifact/org.xerial/sqlite-jdbc -->
    <dependency>
        <groupId>org.xerial</groupId>
        <artifactId>sqlite-jdbc</artifactId>
        <version>3.34.0</version>
    </dependency>

answered Feb 4, 2021 at 15:59

kira kira's user avatar

kira kirakira kira

861 silver badge3 bronze badges

0

All the above solutions works well, when you are dealing with the desktop JAVA Application.
In the case of WebAPP Application, following above solutions will not work.
Actually it is the issue with your App server, that is you needed to add sqlite-jar under your WEB-INF/lib and then only you will be able to run your webapp successfully.

For doing so you can follow below steps:

Go to:

Project-> Properties-> Deployment Assembly-> Add-> Archives From File System -> Next -> Add

Navigate to the folder where you have your sqlite-jar, select it and hit OK.

Click Finish.
OK.

Done, you should be able to run your app now.

Thanks

answered Jul 13, 2017 at 22:26

Yash Bansal's user avatar

Yash BansalYash Bansal

4025 silver badges10 bronze badges

One way that worked for me is to go to JRE System Library -> right clik -> build path -> configure build path -> add external jars -> select the jar and compile.

answered Feb 3, 2015 at 16:13

Xorsist's user avatar

XorsistXorsist

2072 gold badges4 silver badges11 bronze badges

first you can download sqlite-jdbc-3.8.11.2 and after add jar file in your project

Window > Show_view > Package Explorer

step-1: right click on referenced libraries
step-2: select Built path
step-3: configure Built path
step-4: Add External jars file
step-5: add sqlite-jdbc-3.8.11.2
step-6: ok

or second way useful


your project can set the Classpath : Lib/sqlite-jdbc-3.8.11.2.jar

1)create a folder "Lib" in your project workspace 
2)"Lib" folder paste jar file like "sqlite-jdbc-3.8.11.2.jar"
3)After Double click on your project file i.e. 'MANIFEST.MF'
4)select Runtime(Bottom view panel) 
5)plug-in Classpath(Bottom_right position) to add jar file like "Lib/sqlite-jdbc-3.8.11.2.jar"

this working 100% sure..thanks

answered Jan 12, 2017 at 10:55

Chetan Bhagat's user avatar

As said before, add the jar File to your Project.

For Android Studio / IntelliJ you just go this way:

File > Project Structure >

enter image description here

New Module >

enter image description here

Import .JAR/.AAR Package

enter image description here

Now select/add your .jar File and let IntelliJ do the rest.

answered Apr 5, 2017 at 14:44

Paul's user avatar

PaulPaul

8231 gold badge11 silver badges18 bronze badges

Step 1:

Copy sqlite library.


Step 2:

paste the library in ‘WebContent/WEB-INF/lib’ directory you can also do it by selecting ‘lib’ folder in eclipse and pressing
Ctrl + V


Step 3:

Restart the server and hopefully problem should be fixed


answered Jul 25, 2018 at 15:33

Viraj Singh's user avatar

Viraj SinghViraj Singh

1,9711 gold badge17 silver badges27 bronze badges

The java.lang.ClassNotFoundException: org.sqlite.JDBC error occurs when a Java program is unable to find the required JDBC driver for SQLite. This can happen if the driver is not present in the classpath, or if the class is not accessible for any reason. In this case, the error is related to the xerial SQLite JDBC driver. The driver is required to connect to an SQLite database from a Java program.

Method 1: Adding the JDBC Driver to the Classpath

To fix the «java.lang.ClassNotFoundException: org.sqlite.JDBC» error in your Java program, you need to add the JDBC driver to the classpath. Here are the steps to do it:

  1. Download the JDBC driver for SQLite from the Xerial website.
  2. Extract the downloaded file and copy the «sqlite-jdbc-x.x.x.jar» file to a directory on your computer.
  3. Open your command prompt or terminal and navigate to the directory where you saved the «sqlite-jdbc-x.x.x.jar» file.
  4. Compile your Java program with the following command, replacing «Sample.java» with the name of your Java program:
javac -cp .;sqlite-jdbc-x.x.x.jar Sample.java
  1. Run your Java program with the following command, again replacing «Sample» with the name of your Java program:
java -cp .;sqlite-jdbc-x.x.x.jar Sample

Here’s an example Java program that uses the SQLite JDBC driver:

import java.sql.*;

public class Sample {
  public static void main(String[] args) {
    Connection conn = null;
    try {
      // Load the SQLite JDBC driver
      Class.forName("org.sqlite.JDBC");

      // Open a connection to the database
      conn = DriverManager.getConnection("jdbc:sqlite:sample.db");

      // Do something with the connection...

    } catch (ClassNotFoundException e) {
      System.err.println("Could not load JDBC driver");
      e.printStackTrace();
    } catch (SQLException e) {
      System.err.println("Could not connect to database");
      e.printStackTrace();
    } finally {
      // Close the connection
      try {
        if (conn != null) {
          conn.close();
        }
      } catch (SQLException e) {
        System.err.println("Error closing connection");
        e.printStackTrace();
      }
    }
  }
}

In this example, we first load the SQLite JDBC driver using the Class.forName() method. Then we open a connection to the database using the DriverManager.getConnection() method. Finally, we close the connection in a finally block to ensure that it is always closed, even if an exception is thrown.

That’s it! By adding the JDBC driver to the classpath, you should be able to run your Java program without getting the «java.lang.ClassNotFoundException: org.sqlite.JDBC» error.

Method 2: Downloading the Latest JDBC Driver

To fix the java.lang.ClassNotFoundException: org.sqlite.JDBC error in your Java program, you can download the latest JDBC driver for SQLite and add it to your classpath. Here are the steps:

  1. Download the latest JDBC driver for SQLite from the official website: https://github.com/xerial/sqlite-jdbc/releases/latest
  2. Extract the downloaded file to a folder on your computer.
  3. In your Java program, add the following code to load the JDBC driver:
try {
    Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
    System.err.println("Failed to load JDBC driver.");
    e.printStackTrace();
    System.exit(1);
}
  1. Add the path to the extracted JDBC driver JAR file to your classpath. You can do this by specifying the -cp or -classpath option when running your Java program. For example:
java -cp /path/to/sqlite-jdbc-x.xx.xx.jar:. Sample

Note that the . at the end of the classpath specifies the current directory.

  1. Use the JDBC driver to connect to your SQLite database and execute queries. Here is an example:
import java.sql.*;

public class Sample {
    public static void main(String[] args) {
        try (Connection conn = DriverManager.getConnection("jdbc:sqlite:/path/to/database.db");
             Statement stmt = conn.createStatement()) {
            ResultSet rs = stmt.executeQuery("SELECT * FROM table_name");
            while (rs.next()) {
                // process the results
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

In this example, replace /path/to/database.db with the path to your SQLite database file, and table_name with the name of the table you want to query.

That’s it! With these steps, you should be able to fix the java.lang.ClassNotFoundException: org.sqlite.JDBC error in your Java program by downloading the latest JDBC driver for SQLite and adding it to your classpath.

Method 3: Checking the Driver Version Compatibility

To fix the java.lang.ClassNotFoundException: org.sqlite.JDBC error in a Java program that uses SQLite, you can check the compatibility of the SQLite driver version with your program’s Java version. Here’s how to do it:

  1. First, download the latest version of the SQLite JDBC driver from the official website: https://github.com/xerial/sqlite-jdbc/releases

  2. Extract the downloaded ZIP file and copy the sqlite-jdbc-<version>.jar file to your project’s classpath.

  3. In your Java code, add the following lines to load the SQLite driver:

try {
    // Load the SQLite JDBC driver
    Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
    e.printStackTrace();
    System.exit(1);
}
  1. To check the compatibility of the driver version with your Java version, you can use the getMajorVersion() and getMinorVersion() methods of the Driver class:
try {
    // Load the SQLite JDBC driver
    Class.forName("org.sqlite.JDBC");

    // Check the driver version compatibility
    Driver driver = DriverManager.getDriver("jdbc:sqlite:");
    int majorVersion = driver.getMajorVersion();
    int minorVersion = driver.getMinorVersion();
    if (majorVersion < 3 || (majorVersion == 3 && minorVersion < 30)) {
        System.err.println("Error: SQLite JDBC driver version not supported.");
        System.exit(1);
    }
} catch (ClassNotFoundException | SQLException e) {
    e.printStackTrace();
    System.exit(1);
}

In this example, we check if the driver version is at least 3.30, which is compatible with Java 8 and later.

  1. Finally, you can connect to your SQLite database using the DriverManager.getConnection() method:
try {
    // Load the SQLite JDBC driver
    Class.forName("org.sqlite.JDBC");

    // Check the driver version compatibility
    Driver driver = DriverManager.getDriver("jdbc:sqlite:");
    int majorVersion = driver.getMajorVersion();
    int minorVersion = driver.getMinorVersion();
    if (majorVersion < 3 || (majorVersion == 3 && minorVersion < 30)) {
        System.err.println("Error: SQLite JDBC driver version not supported.");
        System.exit(1);
    }

    // Connect to the SQLite database
    Connection conn = DriverManager.getConnection("jdbc:sqlite:/path/to/database.db");
    // ...
} catch (ClassNotFoundException | SQLException e) {
    e.printStackTrace();
    System.exit(1);
}

That’s it! With these steps, you can fix the java.lang.ClassNotFoundException: org.sqlite.JDBC error in your Java program and ensure the compatibility of the SQLite JDBC driver version with your Java version.

Hello, I am following the instructions per xerial’s website, by adding this dependency to my ONOS app’s pom.xml:
https://github.com/xerial/sqlite-jdbc#using-sqlitejdbc-with-maven2

<dependencies>
    <dependency>
      <groupId>org.xerial</groupId>
      <artifactId>sqlite-jdbc</artifactId>
      <version>3.8.6</version>
    </dependency>
</dependencies>

I saw the jar file download just fine. I can even import org.sqlite.JDBC just fine as well. Nonetheless, I still get the following exception:

java.lang.ClassNotFoundException: org.sqlite.JDBC not found by org.tsg.inspector [181]

I am not using IntelliJ, strictly through the CLI and Maven for compilation. Could there be other dependencies that I need? If you have any insight, that would be great!!

  • | Sign In
  • Ask Question

Hi I am integrating SQLite with JDBC and getting the following error. What is wrong?

Exception in thread «main» java.lang.ClassNotFoundException: org.sqlite.JDBC

at java.net.URLClassLoader$1.run(Unknown Source)

at java.net.URLClassLoader$1.run(Unknown Source)

at java.security.AccessController.doPrivileged(Native Method)

at java.net.URLClassLoader.findClass(Unknown Source)

at java.lang.ClassLoader.loadClass(Unknown Source)

at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)

at java.lang.ClassLoader.loadClass(Unknown Source)

at java.lang.Class.forName0(Native Method)

at java.lang.Class.forName(Unknown Source)

Jeet

Replied on August 03, 2015

org.sqlite.JDBC belongs to sqlite-jdbc jar, you need to include this jar in your classpath.

You can use gradle to download jar from maven repository. Find the gardle depedency

compile ‘org.xerial:sqlite-jdbc:3.8.11’

Write Answer

Я пытаюсь заставить класс Xerial Sample работать в Eclipse с sqlite, но я продолжаю получать ошибку «ClassNotFoundException: org.sqlite.JDBC»

Я загрузил файл sqlite-jdbc-3.7.2.jar из https://bitbucket.org/xerial/sqlite-jdbc/downloads. Скопировал его в папку lib в моем проекте «database_test» в eclipse. Затем щелкните правой кнопкой мыши по вкладке «Проект» > «Свойства» > «Путь сборки Java» → «Библиотеки» → Добавить JARs- > Выбрать файл jar. Я пытаюсь выполнить этот код из Xerial, найденного здесь: https://bitbucket.org/xerial/sqlite-jdbc#markdown-header-usage

// load the sqlite-JDBC driver using the current class loader
Class.forName("org.sqlite.JDBC");

Connection connection = null;
try
{
  // create a database connection
  connection = DriverManager.getConnection("jdbc:sqlite:sample.db");
  Statement statement = connection.createStatement();
  statement.setQueryTimeout(30);  // set timeout to 30 sec.

  statement.executeUpdate("drop table if exists person");
  statement.executeUpdate("create table person (id integer, name string)");
  statement.executeUpdate("insert into person values(1, 'leo')");
  statement.executeUpdate("insert into person values(2, 'yui')");
  ResultSet rs = statement.executeQuery("select * from person");
  while(rs.next())
  {
    // read the result set
    System.out.println("name = " + rs.getString("name"));
    System.out.println("id = " + rs.getInt("id"));
  }
}
catch(SQLException e)
{
  // if the error message is "out of memory", 
  // it probably means no database file is found
  System.err.println(e.getMessage());
}
finally
{
  try
  {
    if(connection != null)
      connection.close();
  }
  catch(SQLException e)
  {
    // connection close failed.
    System.err.println(e);
  }
}

}
}

Каждый сайт, о котором я говорил, добавляет файл jar в ваш путь сборки или путь класса, и я считаю, что я это сделал, но ничто не решило проблему. Любая помощь будет оценена по достоинству. Спасибо.

Поделиться

Источник

5 ответов

Спасибо пользователю phew за помощь/идеи.

Я пропустил очевидные инструкции командной строки на сайте Xerial для программы Sample. Чтобы запустить программу из командной строки, мне пришлось скопировать файл JAR в ту же папку, что и программа .java. Затем выполните следующую команду:

java -classpath «.: sqlite-jdbc- (VERSION).jar» Пример

user2646175

Поделиться

Один из способов, который работал у меня, — это перейти в JRE System Library → right clik → build path → configure build path → add external jars → выбрать jar и скомпилировать.

Xorsist

Поделиться

Все вышеперечисленные решения работают хорошо, когда вы имеете дело с настольным приложением JAVA.
В случае приложения WebAPP следующие приведенные выше решения не будут работать.
На самом деле это проблема с вашим сервером приложений, поэтому вам нужно добавить sqlite-jar под свой WEB-INF/lib, и только тогда вы сможете успешно запустить ваш веб-сервер.

Для этого вы можете выполнить следующие шаги:

Перейдите к:

Project- > Properties- > Deployment Assembly- > Add- > Архивы из файловой системы → Далее → Добавить

Перейдите в папку, в которой у вас есть sqlite-jar, выберите ее и нажмите ОК.

Нажмите «Готово».
OK.

Готово, теперь вы можете запустить свое приложение.

Спасибо

Yash Bansal

Поделиться

Как уже говорилось, добавьте файл флага в свой проект.

Для Android Studio/IntelliJ вы просто идите следующим образом:

Файл > Структура проектa >

Изображение 107650

Новый модуль >

Изображение 107651

Импорт пакета .JAR/.AAR

Изображение 107652

Теперь выберите/добавьте файл .jar и дайте IntelliJ сделать все остальное.

padeg

Поделиться

сначала вы можете скачать sqlite-jdbc-3.8.11.2 и после добавления файла jar в свой проект

Window > Show_view > Package Explorer

step-1: right click on referenced libraries
step-2: select Built path
step-3: configure Built path
step-4: Add External jars file
step-5: add sqlite-jdbc-3.8.11.2
step-6: ok

или второй способ полезен


ваш проект может установить Classpath: Lib/sqlite-jdbc-3.8.11.2.jar

1)create a folder "Lib" in your project workspace 
2)"Lib" folder paste jar file like "sqlite-jdbc-3.8.11.2.jar"
3)After Double click on your project file i.e. 'MANIFEST.MF'
4)select Runtime(Bottom view panel) 
5)plug-in Classpath(Bottom_right position) to add jar file like "Lib/sqlite-jdbc-3.8.11.2.jar"

this working 100% sure..thanks

Chetan Bhagat

Поделиться

Ещё вопросы

  • 0Как просмотреть отдельно требуемый идентификатор
  • 0Moodle 2.7 Нужно уметь создавать пользовательское меню для разных групп пользователей
  • 0Не могу знать поведение клика на отключенном элементе
  • 0Один пользователь несколько адресов доставки, как сделать это по умолчанию
  • 1Несколько синхронизированных функций в одном потоке
  • 0Как сделать календарь всплывающим при нажатии на значок календаря?
  • 1контраст с цветовой матрицей
  • 1pg-обещание цепочки запросов для задачи и транзакций
  • 0Получение электронной почты из Facebook GraphObject
  • 0HTML / CSS — Cross Shape с изображением в нем
  • 0Не загружайте часть HTML, пока кнопка не нажата
  • 0Лучший подход к созданию приложения киоска с представлениями, которые меняются по таймеру
  • 0выберите строки, которые удовлетворяют где пункт И строки, которые имеют общий ключ
  • 0Исправление синтаксической ошибки переменной селектора jQuery
  • 0Apache скинул 404 для файла в папке var / www
  • 0Можете ли вы неявно вызвать метод, основанный на объекте
  • 0$ .getJson () предел ответа
  • 1Получить значение вычисляемого свойства в Vue.js и использовать его в свойстве данных
  • 0как найти элемент в тесте транспортира?
  • 1Bing Maps v8 — встроенная канцелярская кнопка SVG не запускает правильный информационный блок
  • 1Обновить значения словаря
  • 0sql приведен из varchar, чтобы удвоить и сэкономить на дубликате ключа
  • 0Приложение Angular показывает только скорректированный динамический контент после обновления
  • 0Класс элемента не отражается после append ()
  • 1Кодирование каждый раз производит разные хэши
  • 1Android, XML: показывать только часть изображения в макете контейнера без изменения соотношения сторон
  • 1Сбой экземпляра Python (obj, tpyes.GeneratorType)
  • 1Начальная настройка Android Realm
  • 0Создание веточки в пространстве имен
  • 0Как загрузить $ scope. $ На последнюю?
  • 0Fitbit oauth регистрация
  • 1Pandas applymap ошибка памяти
  • 0Невозможно получить более 15 строк в angularjs
  • 0Как выбрать в MySQL данные | xx | xx | xx |
  • 1рисование ограничительной рамки на больших изображениях
  • 0Угловой сервис возвращает пустой объект
  • 1как динамически добавлять данные в datatable (Gridview)
  • 1Что LSTM делает с состояниями в пакете? Второй элемент первого пакета наследует состояние от первого элемента первого элемента?
  • 1Рисование TextBox
  • 1Алгоритм: создание шестиугольников с подушкой
  • 0Получить измененные поля
  • 1каковы различия между различными способами создания экземпляра JAVA_HOME в Ubuntu
  • 0Проверка типа шаблонных параметров класса
  • 1Проблема конфигурации Webpack с загрузчиками при запуске gulp serve или build
  • 0Как найти повторяющееся значение значения столбца, используя mysql?
  • 0Ожидаемый возврат алгоритма поиска STL
  • 1Сбой смешивания с ObservableAsPropertyHelper
  • 0Как я глобализирую и управляю массивом символов через функции
  • 0Mysql конвертировать целое число в дату
  • 1Привязать динамически сгенерированный Grid как DataTemplate к HubSection в C #

Сообщество Overcoder

Понравилась статья? Поделить с друзьями:
  • Oracle sql developer ошибка ввода вывода
  • Oracle home key ошибка
  • Oracle exception код ошибки
  • Oracle exception вывести ошибку
  • Oracle 01033 ошибка что значит