簡體   English   中英

Netbeans中的SQLite JDBC:找不到合適的驅動程序

[英]JDBC for SQLite in Netbeans: No suitable driver found

我需要將SQLite文件中的數據加載到我在Netbeans中開發的java程序中。 該文件將通過swing菜單項加載。 我正在使用sqlitejdbc作為驅動程序。

以下是我認為重要的代碼塊:

// header stuff
package aufgabe_9;

import java.sql.*;

//...

// menu item opening the file
private void mitemOpenFileActionPerformed(java.awt.event.ActionEvent evt)  
{                                              

    /**
     * Handles the dialogue for selecting and loading file.
     */
    JFileChooser fileChoose = new JFileChooser();
    fileChoose.showOpenDialog(this); //'this' calls the current object

     //Load the sql file
     try {
        String filePath = fileChoose.getSelectedFile().toString();
        Connection conn = DriverManager.getConnection("jdbc:sqlite:" +  
                    filePath);

        //Close the connection
        if (conn != null)
            conn.close();

    }


    catch (SQLException e){System.err.println("Database problem: " + e);}
    }                                  
}

//...

運行程序並通過菜單加載文件時,出現以下錯誤:

java.sql.SQLException: No suitable driver found for jdbc:sqlite:/home/levent
/temp/A9AProbeflaeche.db

在閱讀了各自的stackexchange帖子之后,我明白這個問題可能是由於(1)格式錯誤的文件URL或(2)未加載驅動程序引起的。 以下是一些進一步的信息:

  • 我通過Tools - > Libraries將sqlitejdbc-3.7.2.jar添加到庫類路徑中,並通過Window - > Projects添加到項目庫中。
  • 我還使用此函數檢查了Classpath 它包含jdbc jar文件的路徑,正如預期的那樣。
  • 我可以通過“ 服務”菜單連接到數據庫而沒有任何問題,因此我可以假設URL正確,以及在我的系統上運行的sqlite。
  • 一些操作系統信息:我在64位ARCH Linux 3.12.9-2上運行Netbeans 8.0。

任何人都可以告訴我我在這里缺少什么嗎? 任何幫助贊賞!

問題解決了以下代碼對我有用:

//...
private void mitemOpenFileActionPerformed(java.awt.event.ActionEvent evt)   
{                                              

    /**
    * Handles the dialogue for selecting and loading file.
    */
    JFileChooser fileChoose = new JFileChooser();
    fileChoose.showOpenDialog(this); 

    //Load the sql file
    try {
        //Get file path
        String filePath = fileChoose.getSelectedFile().toString();

        //Open connection
        Class.forName("org.sqlite.JDBC");
        Connection conn = DriverManager.getConnection("jdbc:sqlite:" + filePath);

        //Do stuff...                       

        //Close the connection
        conn.close();

    }

    //"Multicatch":
    catch (SQLException | ClassNotFoundException e) { 
    System.err.println("Database problem: " + e);
}
//...

您可能需要加載驅動程序類,以便使用以下代碼將自身注冊到DriverManager:Class.forName(“org.sqlite.JDBC”);

注意:這只需要在您的應用程序中調用一次。

這是Java包含ServiceLoader API之前的標准過程,現在DriverManager使用該API來注冊它在類路徑中找到的驅動程序,但驅動程序需要聲明一個名為java.sql.Driver的文件,其中包含驅動程序類的名稱在他們的jar的目錄META-INF \\ services中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM