当前位置: 首页 > 面试题库 >

将嵌入式数据库打包到jar文件中

柯国安
2023-03-14
问题内容

我在eclipse项目中创建了一个derby嵌入式数据库,它在eclipse上运行良好,但是当将该项目打包到Runnable
jar文件中时,它无法连接数据库。

我已经完成了与此视频类似的操作 http://vinayakgarg.wordpress.com/2012/03/07/packaging-java-
application-with-apache-derby-as-jar-executable-using-
eclipse/

这是我的 Communicate.java

import java.io.File;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Communicate {

private static final String dbURL = "jdbc:derby:imagesDB;create=true";
private static final String tableName = "imageDB";
private static Connection conn = null;
private static Statement stmt = null;

public void insert(String path, String hash, long FileSize,
        String label_name) throws NoSuchAlgorithmException, Exception {
    try {
        stmt = conn.createStatement();
        stmt.execute("insert into " + tableName + " values (\'" + path
                + "\'," + FileSize + ",\'" + hash + "\'" + ",\'"
                + label_name + "\')");
        stmt.close();
    } catch (SQLException sqlExcept) {
        sqlExcept.printStackTrace();
    }
}

public void createConnection() {
    try {
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
        // Get a connection
        conn = DriverManager.getConnection(dbURL);
    } catch (Exception except) {
        except.printStackTrace();
    }
}

public void createTable() throws SQLException {
    Statement st = conn.createStatement();
    st.execute("CREATE TABLE "
            + tableName
            + " (fullPath VARCHAR(512), fileSize INTEGER, md5 VARCHAR(512), label_name VARCHAR(100))");
}

public void indexTable() throws SQLException {
    Statement st = conn.createStatement();
    st.execute("CREATE INDEX imageDBIndex ON imageDB (fullPath, label_name)");
}

public void deleteTable() throws SQLException {
    Statement st = conn.createStatement();
    st.execute("drop table " + tableName);
}

public String searchBySizeAndMD(String file_path, long size, String hash)
        throws SQLException {
    StringBuilder sb = new StringBuilder();
    Statement st = conn.createStatement();
    ResultSet rs = st
            .executeQuery("SELECT fullPath, label_name FROM (SELECT * FROM imageDB im WHERE im.fileSize = "
                    + size + " ) as A WHERE A.md5 = " + "\'" + hash + "\'");
    while (rs.next()) {
        sb.append("Image: (" + rs.getString("fullPath")
                + ") is at label: (" + rs.getString("label_name") + ")\n");
    }
    return sb.toString();
}

public String searchByImageName(String fileName) throws SQLException {
    StringBuilder sb = new StringBuilder();
    Statement st = conn.createStatement();
    ResultSet rs = st
            .executeQuery("SELECT fullPath, label_name FROM imageDB im WHERE im.fullPath like \'%"
                    + fileName + "%\'");
    while (rs.next()) {
        File out_path = new File(rs.getString("fullPath"));
        if (!fileName.equals(out_path.getName())) continue;
        sb.append("Image: (" + out_path.getPath()
                + ") is at label: (" + rs.getString("label_name") + ")\n");
    }

    return sb.toString();
}

public void deleteLabel(String label) throws SQLException {
    Statement st = conn.createStatement();
    st.execute("DELETE FROM " + tableName + " WHERE label_name = \'" + label + "\'");       
}
 }

这个问题有帮助吗?


问题答案:

数据库应位于运行jar的文件夹中。如果不是,请检查docs如何指定connectionURL。如果将项目导出到可运行的jar文件,请指定不解压缩相关库,而不必将其直接提取到jar或本地lib文件夹中。这些库位于derby.jar并且derbytools.jar应该位于类路径或清单类路径中。使用以下代码测试您的

Communicate 类。

import java.io.File;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Communicate {

  private static final String dbURL = "jdbc:derby:imagesDB;create=true";
  private static final String tableName = "imageDB";
  private static Connection conn = null;
  private static Statement stmt = null;

  public void insert(String path, String hash, long FileSize,
                     String label_name) throws NoSuchAlgorithmException, Exception {
    try {
      stmt = conn.createStatement();
      stmt.execute("insert into " + tableName + " values (\'" + path
        + "\'," + FileSize + ",\'" + hash + "\'" + ",\'"
        + label_name + "\')");
      stmt.close();
      System.out.println("Inserted into table "+ tableName+ " values (\'" + path
        + "\'," + FileSize + ",\'" + hash + "\'" + ",\'"
        + label_name + "\')");
    } catch (SQLException sqlExcept) {
      sqlExcept.printStackTrace();
    }
  }

  public void loadDriver() {
    try {
      Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
      System.out.println("Loaded the appropriate driver");
    } catch (Exception except) {
      except.printStackTrace();
    }
  }

  public void createConnection() {
    try {
      // Get a connection
      conn = DriverManager.getConnection(dbURL);
      System.out.println("Connected to and created database ");
    } catch (Exception except) {
      except.printStackTrace();
    }
  }

  public void createTable() throws SQLException {
    Statement st = conn.createStatement();
    st.execute("CREATE TABLE "
      + tableName
      + " (fullPath VARCHAR(512), fileSize INTEGER, md5 VARCHAR(512), label_name VARCHAR(100))");
    System.out.println("Created table "+ tableName);
  }

  public void indexTable() throws SQLException {
    Statement st = conn.createStatement();
    st.execute("CREATE INDEX imageDBIndex ON imageDB (fullPath, label_name)");
    System.out.println("Created index "+ "imageDBIndex");
  }

  public void deleteTable() throws SQLException {
    Statement st = conn.createStatement();
    st.execute("drop table " + tableName);
    System.out.println("Deleted table "+ tableName);
  }

  public String searchBySizeAndMD(String file_path, long size, String hash)
    throws SQLException {
    StringBuilder sb = new StringBuilder();
    Statement st = conn.createStatement();
    ResultSet rs = st
      .executeQuery("SELECT fullPath, label_name FROM (SELECT * FROM imageDB im WHERE im.fileSize = "
        + size + " ) as A WHERE A.md5 = " + "\'" + hash + "\'");
    while (rs.next()) {
      sb.append("Image: (" + rs.getString("fullPath")
        + ") is at label: (" + rs.getString("label_name") + ")\n");
    }
    return sb.toString();
  }

  public String searchByImageName(String fileName) throws SQLException {
    StringBuilder sb = new StringBuilder();
    Statement st = conn.createStatement();
    ResultSet rs = st
      .executeQuery("SELECT fullPath, label_name FROM imageDB im WHERE im.fullPath like \'%"
        + fileName + "%\'");
    while (rs.next()) {
      File out_path = new File(rs.getString("fullPath"));
      if (!fileName.equals(out_path.getName())) continue;
      sb.append("Image: (" + out_path.getPath()
        + ") is at label: (" + rs.getString("label_name") + ")\n");
    }

    return sb.toString();
  }

  public void deleteLabel(String label) throws SQLException {
    Statement st = conn.createStatement();
    st.execute("DELETE FROM " + tableName + " WHERE label_name = \'" + label + "\'");
  }

  public static void main(String[] args)
  {
    Communicate c = new Communicate();
    c.loadDriver();
    try {
      c.createConnection();
      c.createTable();
      c.indexTable();
      c.insert("/some/path", "12323423", 45656567, "label name");
      String s = c.searchBySizeAndMD("/some/path", 45656567, "12323423");
      System.out.println("Search result: "+ s);
      c.deleteTable();
      conn.commit();
      System.out.println("Committed the transaction");

      //Shutdown embedded database
      try
      {
        // the shutdown=true attribute shuts down Derby
        DriverManager.getConnection("jdbc:derby:;shutdown=true");

      }
      catch (SQLException se)
      {
        if (( (se.getErrorCode() == 50000)
          && ("XJ015".equals(se.getSQLState()) ))) {
          // we got the expected exception
          System.out.println("Derby shut down normally");
        } else {
          System.err.println("Derby did not shut down normally");
          System.err.println("  Message:    " + se.getMessage());
        }
      }

    } catch (Exception e) {
      System.err.println("  Message:    " + e.getMessage());
    } finally {
      // release all open resources to avoid unnecessary memory usage

      //Connection
      try {
        if (conn != null) {
          conn.close();
          conn = null;
        }
      } catch (SQLException e) {
        System.err.println("  Message:    " + e.getMessage());
      }
    }
    System.out.println("Communicate finished");
  }


}

这是输出:

Loaded the appropriate driver
Connected to and created database 
Created table imageDB
Created index imageDBIndex
Inserted into table imageDB values ('/some/path',45656567,'12323423','label name')
Search result: Image: (/some/path) is at label: (label name)

Deleted table imageDB
Committed the transaction
Derby shut down normally
Communicate finished


 类似资料:
  • 本文向大家介绍浅谈将JNI库打包入jar文件,包括了浅谈将JNI库打包入jar文件的使用技巧和注意事项,需要的朋友参考一下 在Java开发时,我们有时候会接触到很多本地库,这样在对项目打包的时候我们不得不面临一个选择:要么将库文件与包好的jar文件放在一起;要么将库文件包入jar。 将一个不大的项目包成一个jar有诸多发布优势,本次将分享一个将JNI包入jar的方法。 [实现思路] 将JNI库(d

  • 问题内容: 我正在为桌子写夹具。并且其中之一接受JSON字符串作为值。 问题是灯具未加载失败,原因是: 任何解决方案。 问题答案: 我认为将引号括起来应该可以解决问题:

  • 我正在构建一个将使用neo4j的web应用程序。我将在Java构建一个REST API,它将使用Neo4j嵌入式版本。这个架构有什么问题吗? 用别的方法好吗?Neo4j服务器? 谢谢!

  • 问题内容: 我想知道使用可运行的jar文件创建将库从eclipse提取和打包成jar文件之间的区别。 如果我的程序(可运行的jar)使用需要这些外部库(jar)的其他类,我应该选择什么? 问题答案: 如果要将jar放入生成的jar文件中,则可以使用打包方法。例如,如果您使用的是Apache库或其他一些第三方的jar,则可能需要将这些jar保存在生成​​的jar中。在这种情况下,请使用包装。 “将所

  • 问题内容: 我正在做一个Maven项目。当在一个想法中编译和运行我的项目时,一切都很好,但是每当我创建jar文件时,都无法将web / lib /中的外部jar文件复制到jar文件中。为什么会发生这种情况?我可以将所有文件插入jar文件吗? 问题答案: 是的,我找到了解决方案。

  • 问题内容: 我将H2数据库用于嵌入式模式的桌面应用程序。当我将应用程序压缩到jar文件中时,将省略数据库文件。因此,当我运行MyApplication.jar时,没有任何效果。用MyApplication.jar嵌入/包含/连接h2.jar文件的正确方法是什么?也许还有另一种在捆绑包中交付数据库和应用程序的方法? 问题答案: 一种常见的方案是在相对于您的应用程序的目录中放置一个条目,并将其条目包含