在独立 Java 应用程序中设置嵌入式 Derby 数据库

发布于 2024-10-06 21:47:43 字数 540 浏览 9 评论 0原文

我正在尝试为独立的 Java 应用程序设置嵌入式 Derby 数据库,但在翻阅各种文档后,我似乎找不到任何简单的解释或示例。我正在使用 Eclipse 和 Derby 插件,并为我的项目启用了 Derby nature。

我在 独立地址簿 以及在 Eclipse 中使用 Derby 的概述(似乎没有涵盖嵌入式部署),但我仍然觉得我缺少一些基本的东西。

这是我第一次尝试通过 Java 使用数据库,我有点困惑,所以这里是我的基本问题:

  • Java 如何与 Derby 数据库交互的基本理念(或模型)(在嵌入式部署中)是什么? ?是否要遵循它们的重要设计模式?
  • 我是否需要在类中创建某种类型的数据库构造函数(包括表结构等),或者这一切都是用其他工具完成的?
  • 创建并保存数据库后,如何“启动”它?实际的数据库保存在哪里?

代码片段会非常有帮助!

I'm trying to setup an embedded Derby database for a standalone Java application, but after pouring through all sorts of documentation, I just can't seem to find any simple explanations or examples. I'm using Eclipse with the Derby plugin and have enabled Derby nature for my project.

I found an example of using an embedded Derby database in a standalone address book as well as an overview of using Derby in Eclipse (that doesn't seem to cover the embedded deployment), but I still feel like I'm missing something fundamental.

This is my first time attempting to use a database with Java, and I'm a little confused, so here are my basic questions:

  • What's the basic philosophy (or model) for how Java interacts with a Derby database (in an embedded deployment)? Are their important design patterns to be followed?
  • Do I need to create some type of database constructor (that includes table structure, etc.) in a class, or is that all done with some other tool?
  • One the database is created and saved, how do I "start" it up? And where is the actual database saved?

Snippets of code would be very helpful!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

情场扛把子 2024-10-13 21:47:43

要在 Java 中以嵌入模式使用 Derby,我们需要执行以下步骤:

  • 使用 org.apache.derby.jdbc.EmbeddedDriver 驱动程序,位于
    derbyclient Maven 依赖项
  • 使用嵌入模式的连接字符串: jdbc:derby:dbname
  • 设置 Derby 系统主目录:
    System.setProperty("derby.system.home", "/home/janbodnar/.derby");
  • 最后以编程方式关闭 Derby:
    DriverManager.getConnection("jdbc:derby:;shutdown=true");
  • 处理 XJ015 错误,该错误在成功关闭时触发

完整的工作示例可以在我的 Java JDBC Derby 编程教程

To use Derby in Java in embedded mode, we need to do the following steps:

  • Use the org.apache.derby.jdbc.EmbeddedDriver driver, located in
    the derbyclient Maven dependency
  • Use the connection string for embedded mode: jdbc:derby:dbname
  • Set up the Derby system home:
    System.setProperty("derby.system.home", "/home/janbodnar/.derby");
  • Shut down Derby programatically at the end:
    DriverManager.getConnection("jdbc:derby:;shutdown=true");
  • Handle XJ015 error, which is triggered at successfull shutdown

Full working examples can be found at my Java JDBC Derby programming tutorial.

过潦 2024-10-13 21:47:43

我建议您使用一个名为 ConnectionDerby 的类,其中将所有逻辑和参数放入选择、插入、更新、删除,并且作为嵌入式数据库,我将检查数据库是否已存在,如果不存在,则我创建,我希望这样代码可以帮助你,对不起,我的英语,我是在java中使用这个数据库的新手,但我希望这可以帮助你理解......

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;

public class ConnectionDerby {

    private Connection conn = null;
    private Statement sttm = null;

    public Connection CrearBD(String query) {
    try {
        //Obtenemos el Driver de Derby
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        conn = DriverManager.getConnection("jdbc:derby:.\\BD\\nombrebasededatos.db;create=true");
        if (conn != null) {
            //JOptionPane.showMessageDialog(null, "Base de Datos Lista");
            try {
                PreparedStatement pstm = conn.prepareStatement(query);
                pstm.execute();
                pstm.close();
                //JOptionPane.showMessageDialog(null, "Base de Datos Creada Correctamente");
                System.out.println("SENTENCIA SQL EFECTUADA CORRECTAMENTE");
            } catch (SQLException ex) {
                //JOptionPane.showMessageDialog(null, ex.getLocalizedMessage());
                System.out.println(ex.getMessage());
                JOptionPane.showMessageDialog(null, "NO SE PUDO EFECTUAR LA SENTENCIA SQL", "Error", JOptionPane.ERROR_MESSAGE);
                //JOptionPane.showMessageDialog(null, "NO SE PUDO EFECTUAR LA SENTENCIA SQL");
            }
        }

    } catch (SQLException e) {
        System.out.println(e.getMessage());
        JOptionPane.showMessageDialog(null, "NO SE PUDO EFECTUAR LA SENTENCIA SQL", "Error", JOptionPane.ERROR_MESSAGE);
        //JOptionPane.showMessageDialog(null, "TRONO LA APLICACION EN EJECUTAR LAS SENTENCIAS SQL parte 2");
    } catch (ClassNotFoundException e) {
        System.out.println(e.getMessage());
        JOptionPane.showMessageDialog(null, "NO SE PUDO EFECTUAR LA SENTENCIA SQL", "Error", JOptionPane.ERROR_MESSAGE);
        //JOptionPane.showMessageDialog(null, "TRONO LA APLICACION EN EJECUTAR LAS SENTENCIAS SQL parte 3");
    }
    return conn;
}

public Connection AccederBD() {
    try {
        //Obtenemos el Driver de Derby
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        //Obtenemos la Conexión
        conn = DriverManager.getConnection("jdbc:derby:.\\BD\\nombrebasededatos.db");
        if (conn != null) {
            System.out.println("Base de Datos Ya Leida Correctamente");
            //JOptionPane.showMessageDialog(null, "Base de Datos Ya Leida Correctamente");
        }
    } catch (SQLException e) {
        System.out.println(e.getMessage());
        System.out.println("Sistema Creado por Mario José Echeverría");
        System.out.println("NO SE ENCONTRO LA BASE DE DATOS");
        System.out.println("CREANDO BASE DE DATOS EN DERBY DATABASE");
        String createTableProyecto = "Sentence to create first table";
        String createTablePrimer = "Sentence to create second table";
        String createTableTopCoat = "Sentence to create third table";
        String createTableCotizacion = "Sentence to create fourth table";
        CrearBD(createTableProyecto);
        CrearBD(createTablePrimer);
        CrearBD(createTableTopCoat);
        CrearBD(createTableCotizacion);
        //*************PRUEBAS*****************
    } catch (ClassNotFoundException e) {
        System.out.println(e.getMessage());
        System.out.println("ERROR DE TIPO ClassNotFoundException");
        //JOptionPane.showMessageDialog(null, "TRONO LA APLICACION EN ACCEDER A LA BASE DE DATOS parte 2");
    }
    return conn;
}

public void UID(String sqlcad) {
    try {
        //Obtenemos el Driver de Derby
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        conn = DriverManager.getConnection("jdbc:derby:.\\BD\\nombrebasededatos.db");
        sttm = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        sttm.executeUpdate(sqlcad);
        System.out.println("Conexión Exitosa a la Base de Datos");
        //JOptionPane.showMessageDialog(null, "Conexión exitosa");
        sttm.close();
        conn.close();
        if (conn != null) {
            System.out.println("Consulta Realizada Correctamente");
            //JOptionPane.showMessageDialog(null, "Base de Datos Ya Leida Correctamente");
        }
    } catch (SQLException e) {
        System.out.println("Error= " + e.getMessage());
    } catch (ClassNotFoundException e) {
        System.out.println("Error= " + e.getMessage());
    }
}

public ResultSet getvalores(String sqlcad) {
    ResultSet rs = null;
    try {
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        conn = DriverManager.getConnection("jdbc:derby:.\\BD\\nombrebasededatos.db");
        sttm = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        //String sqlcad = "Select nombre, m2xgal, pregal, precub, descripcion from primer";
        rs = sttm.executeQuery(sqlcad);
        return rs;
    } catch (Exception e) {
        System.out.println("Error= " + e.getMessage());
        return rs;
    }
}
}

I suggest that you use a class named ConnectionDerby, where put all the logic and the parameters to Select, insert, update, Delete, and as a embedded database i comprobate if a database already exists, if not exists i created then, i hope this code help you, sorry or my english and i am newbie using this database in java, but i hope this help you to understand....

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;

public class ConnectionDerby {

    private Connection conn = null;
    private Statement sttm = null;

    public Connection CrearBD(String query) {
    try {
        //Obtenemos el Driver de Derby
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        conn = DriverManager.getConnection("jdbc:derby:.\\BD\\nombrebasededatos.db;create=true");
        if (conn != null) {
            //JOptionPane.showMessageDialog(null, "Base de Datos Lista");
            try {
                PreparedStatement pstm = conn.prepareStatement(query);
                pstm.execute();
                pstm.close();
                //JOptionPane.showMessageDialog(null, "Base de Datos Creada Correctamente");
                System.out.println("SENTENCIA SQL EFECTUADA CORRECTAMENTE");
            } catch (SQLException ex) {
                //JOptionPane.showMessageDialog(null, ex.getLocalizedMessage());
                System.out.println(ex.getMessage());
                JOptionPane.showMessageDialog(null, "NO SE PUDO EFECTUAR LA SENTENCIA SQL", "Error", JOptionPane.ERROR_MESSAGE);
                //JOptionPane.showMessageDialog(null, "NO SE PUDO EFECTUAR LA SENTENCIA SQL");
            }
        }

    } catch (SQLException e) {
        System.out.println(e.getMessage());
        JOptionPane.showMessageDialog(null, "NO SE PUDO EFECTUAR LA SENTENCIA SQL", "Error", JOptionPane.ERROR_MESSAGE);
        //JOptionPane.showMessageDialog(null, "TRONO LA APLICACION EN EJECUTAR LAS SENTENCIAS SQL parte 2");
    } catch (ClassNotFoundException e) {
        System.out.println(e.getMessage());
        JOptionPane.showMessageDialog(null, "NO SE PUDO EFECTUAR LA SENTENCIA SQL", "Error", JOptionPane.ERROR_MESSAGE);
        //JOptionPane.showMessageDialog(null, "TRONO LA APLICACION EN EJECUTAR LAS SENTENCIAS SQL parte 3");
    }
    return conn;
}

public Connection AccederBD() {
    try {
        //Obtenemos el Driver de Derby
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        //Obtenemos la Conexión
        conn = DriverManager.getConnection("jdbc:derby:.\\BD\\nombrebasededatos.db");
        if (conn != null) {
            System.out.println("Base de Datos Ya Leida Correctamente");
            //JOptionPane.showMessageDialog(null, "Base de Datos Ya Leida Correctamente");
        }
    } catch (SQLException e) {
        System.out.println(e.getMessage());
        System.out.println("Sistema Creado por Mario José Echeverría");
        System.out.println("NO SE ENCONTRO LA BASE DE DATOS");
        System.out.println("CREANDO BASE DE DATOS EN DERBY DATABASE");
        String createTableProyecto = "Sentence to create first table";
        String createTablePrimer = "Sentence to create second table";
        String createTableTopCoat = "Sentence to create third table";
        String createTableCotizacion = "Sentence to create fourth table";
        CrearBD(createTableProyecto);
        CrearBD(createTablePrimer);
        CrearBD(createTableTopCoat);
        CrearBD(createTableCotizacion);
        //*************PRUEBAS*****************
    } catch (ClassNotFoundException e) {
        System.out.println(e.getMessage());
        System.out.println("ERROR DE TIPO ClassNotFoundException");
        //JOptionPane.showMessageDialog(null, "TRONO LA APLICACION EN ACCEDER A LA BASE DE DATOS parte 2");
    }
    return conn;
}

public void UID(String sqlcad) {
    try {
        //Obtenemos el Driver de Derby
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        conn = DriverManager.getConnection("jdbc:derby:.\\BD\\nombrebasededatos.db");
        sttm = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        sttm.executeUpdate(sqlcad);
        System.out.println("Conexión Exitosa a la Base de Datos");
        //JOptionPane.showMessageDialog(null, "Conexión exitosa");
        sttm.close();
        conn.close();
        if (conn != null) {
            System.out.println("Consulta Realizada Correctamente");
            //JOptionPane.showMessageDialog(null, "Base de Datos Ya Leida Correctamente");
        }
    } catch (SQLException e) {
        System.out.println("Error= " + e.getMessage());
    } catch (ClassNotFoundException e) {
        System.out.println("Error= " + e.getMessage());
    }
}

public ResultSet getvalores(String sqlcad) {
    ResultSet rs = null;
    try {
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        conn = DriverManager.getConnection("jdbc:derby:.\\BD\\nombrebasededatos.db");
        sttm = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        //String sqlcad = "Select nombre, m2xgal, pregal, precub, descripcion from primer";
        rs = sttm.executeQuery(sqlcad);
        return rs;
    } catch (Exception e) {
        System.out.println("Error= " + e.getMessage());
        return rs;
    }
}
}
时光匆匆的小流年 2024-10-13 21:47:43

如果您同意切换到 netbeans IDE,这里有两个有用的教程,我可以在 ide 中使用它们(我在安装程序方面遇到了一些小问题)。它使用 JPA,这是一种简化大量数据库交互的抽象。

https://blogs.oracle.com/geertjan/entry/embedded_database_for_netbeans_platform

http://platform.netbeans.org/tutorials/nbm-crud.html

到地址您的一些疑问:

  1. 如果您使用 java 和关系数据库,我强烈推荐
    JPA。否则,您将使用 JDBC 与数据库交互,并且
    使用 SQL。
  2. 传统上,您使用实用程序或运行脚本来
    但是创建表模式,因为您要嵌入您
    可能有兴趣(就像我一样)让数据库和模式创建它
    self 动态,这样你就不必每次都运行这个脚本
    安装您的应用程序。这可以通过 derby 的嵌入式 JPA 实现
    本教程涵盖的配置。
  3. 如果您正在运行
    嵌入式 derby 数据库没有单独的线程或套接字
    你启动。您的应用程序将使用 jpa 或 derby api,它将使用
    文件锁定以访问 derby 文件。在我的定义中嵌入
    数据库没有单独的线程或进程侦听套接字
    处理多个请求。

希望这有帮助,祝你好运!

If you're ok with switching to the netbeans IDE here are two useful tutorials which I was able to get working in the ide (i'm having some minor issues with the installer). It uses JPA which is an abstraction that simplifies a lot of database interaction.

https://blogs.oracle.com/geertjan/entry/embedded_database_for_netbeans_platform

http://platform.netbeans.org/tutorials/nbm-crud.html

To address some of your inquiries:

  1. If you're using java and relation dbs i would highly recommend
    JPA. Otherwise you are using JDBC to interact with your database and
    using SQL.
  2. Traditionally you use a utility or run a script to
    create the table schema however since you are going for embedded you
    might be interested (as i am) in having the db and schema create it
    self dynamically so you don't have to run this script every time you
    install your application. This is doable with derby's embedded JPA
    configuration which the tutorial covers.
  3. if you are running an
    embedded derby database there is no separate thread or socket that
    you start up. you app will use the jpa or derby api which will use
    file locking to access the derby files. In my definition an embedded
    database does not have a separate thread or process listening on a socket
    handling multiple request.

Hope this helps and Good luck!

东走西顾 2024-10-13 21:47:43

I never did derby (although did once mysql) and got all going from this simple example. Actually I did not even read the talk - I just did scroll to the middle where self-explanatory example is.

给我一枪 2024-10-13 21:47:43

这些博客和 url 非常精彩,但我建议 OP 切换到 NetBeans,即使我使用了 Java Derby 驱动程序的 d ClientDriver 版本,并且我创建了一个类或方法来在启动时自动启动数据库正常运行时间,这样我在运行时就不会遇到任何 SQLException 并且它一直在工作。虽然我确实使用 NetworkServerControl 类在运行时启动我的数据库,就像 diz 一样

NetworkServerControl server=new NetworkServerControl(InetAddress.getLocalHost(),1527);
server.start (null);
//Class.forName n DriverManager.getConnection() declarations goes here. 

Those blogs n url are very wonderful but I will suggest the OP switch over to NetBeans even though I used d ClientDriver version of Java Derby drivers and I create a class or method to start up the database automatically at start up time so that I don't encounter any SQLException at run time and it has been working. Though I do use NetworkServerControl class to start up my database at run time going like diz

NetworkServerControl server=new NetworkServerControl(InetAddress.getLocalHost(),1527);
server.start (null);
//Class.forName n DriverManager.getConnection() declarations goes here. 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文