首页 > 数据库 >Derby 数据库介绍(2)--使用

Derby 数据库介绍(2)--使用

时间:2024-12-22 18:53:08浏览次数:3  
标签:jdbc String -- 数据库 Derby user derby public con

本文主要介绍 Derby 的基本使用(简介可参考:Derby 数据库介绍(1)--简介),文中所使用到的软件版本:Java 1.8.0_341、Derby 10.14.2.0。

1、嵌入模式

直接使用 JDBC 连接数据库,可创建和启动数据库。

1.1、内存数据库

@Test
public void embeddedMemory() throws SQLException {
    String user = "admin";
    Connection con = JdbcUtil.getConnection("org.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:memory:myDb;create=true", user, "");
    business(con, user);
    con.close();
}

private void business(Connection con, String user) throws SQLException {
    String tableName = "a_student";
    Statement st = con.createStatement();
    String sql = "select 1 from sys.sysTABLES a,sys.sysschemas b where a.schemaid=b.schemaid and upper(b.schemaname)=? and upper(a.tablename)=?";
    PreparedStatement pst = con.prepareStatement(sql);
    pst.setString(1, user.toUpperCase());
    pst.setString(2, tableName.toUpperCase());
    ResultSet rs = pst.executeQuery();
    if (!rs.next()) {//表不存在则创建并初始化数据,这里根据业务需要进行操作
        st.executeUpdate("create table " + tableName + "(id int, name varchar(32))");
        st.executeUpdate("insert into " + tableName + "(id,name) values (1,'李白')");
        st.executeUpdate("insert into " + tableName + "(id,name) values (2,'杜甫')");
    }

    rs = st.executeQuery("select * from " + tableName);
    while (rs.next()) {
        log.info("id={},name={}", rs.getInt("id"), rs.getString("name"));
    }
}

1.2、文件数据库

@Test
public void embeddedFile() throws SQLException {
    String user = "admin";
    Connection con = JdbcUtil.getConnection("org.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:d:/temp/myDb;create=true", user, "");
    business(con, user);
    con.close();
}

1.3、资源数据库

@Test
public void embeddedJar() throws SQLException {
    String user = "admin";
    Connection con = JdbcUtil.getConnection("org.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:classpath:myDb", user, "");
    business(con, user);
    con.close();
}

jar 包不在 classpath 之中:

@Test
public void embeddedJar2() throws SQLException {
    String user = "admin";
    Connection con = JdbcUtil.getConnection("org.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:jar:(d:/temp/my.jar)myDb", user, "");
    business(con, user);
    con.close();
}

2、服务器模式

在服务端启动 Derby 数据库服务:

cd ${DERBY_HOME}/bin
NetworkServerControl.bat start -p 1527 -noSecurityManager

客户端通过 JDBC 访问 Derby 服务。

2.1、内存数据库

@Test
public void networkMemory() throws SQLException {
    String user = "admin";
    Connection con = JdbcUtil.getConnection("org.apache.derby.jdbc.ClientDriver", "jdbc:derby://localhost:1527/memory:myDb;create=true", user, "123456");
    business(con, user);
    con.close();
}

2.2、文件数据库

@Test
public void networkFile() throws SQLException {
    String user = "admin";
    Connection con = JdbcUtil.getConnection("org.apache.derby.jdbc.ClientDriver", "jdbc:derby://localhost:1527/d:/temp/myDb;create=true", user, "123456");
    business(con, user);
    con.close();
}

2.3、资源数据库

@Test
public void networkJar() throws SQLException {
    String user = "admin";
    Connection con = JdbcUtil.getConnection("org.apache.derby.jdbc.ClientDriver", "jdbc:derby://localhost:1527/classpath:myDb", user, "123");
    business(con, user);
    con.close();
}

jar 包不在 classpath 之中:

@Test
public void networkJar2() throws SQLException {
    String user = "admin";
    Connection con = JdbcUtil.getConnection("org.apache.derby.jdbc.ClientDriver", "jdbc:derby://localhost:1527/jar:(d:/temp/my.jar)myDb", user, "123");
    business(con, user);
    con.close();
}

3、混合模式

应用通过代码的方式启动数据库服务,应用内访问数据库可以使用进程模式,其他应用通过服务器模式访问。

@Test
public void networkServerControl() throws Exception {
    NetworkServerControl server = new NetworkServerControl(InetAddress.getByName("0.0.0.0"), 1527);
    server.start (null);

    CountDownLatch countDownLatch = new CountDownLatch(1);
    new Thread(() -> {
        try {
            //模拟其他应用访问
            networkMemory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        countDownLatch.countDown();
    }).start();

    countDownLatch.await();
    server.shutdown();
}

 

 

完整代码:

package com.abc.demo.db;

import lombok.extern.slf4j.Slf4j;
import org.apache.derby.drda.NetworkServerControl;
import org.junit.Test;

import java.net.InetAddress;
import java.sql.*;
import java.util.concurrent.CountDownLatch;

@Slf4j
public class DerbyCae {
    @Test
    public void embeddedMemory() throws SQLException {
        String user = "admin";
        Connection con = JdbcUtil.getConnection("org.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:memory:myDb;create=true", user, "");
        business(con, user);
        con.close();
    }

    @Test
    public void embeddedFile() throws SQLException {
        String user = "admin";
        Connection con = JdbcUtil.getConnection("org.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:d:/temp/myDb;create=true", user, "");
        business(con, user);
        con.close();
    }

    @Test
    public void embeddedJar() throws SQLException {
        String user = "admin";
        Connection con = JdbcUtil.getConnection("org.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:classpath:myDb", user, "");
        business(con, user);
        con.close();
    }

    @Test
    public void embeddedJar2() throws SQLException {
        String user = "admin";
        Connection con = JdbcUtil.getConnection("org.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:jar:(d:/temp/my.jar)myDb", user, "");
        business(con, user);
        con.close();
    }

    @Test
    public void networkMemory() throws SQLException {
        String user = "admin";
        Connection con = JdbcUtil.getConnection("org.apache.derby.jdbc.ClientDriver", "jdbc:derby://localhost:1527/memory:myDb;create=true", user, "123456");
        business(con, user);
        con.close();
    }

    @Test
    public void networkFile() throws SQLException {
        String user = "admin";
        Connection con = JdbcUtil.getConnection("org.apache.derby.jdbc.ClientDriver", "jdbc:derby://localhost:1527/d:/temp/myDb;create=true", user, "123456");
        business(con, user);
        con.close();
    }

    @Test
    public void networkJar() throws SQLException {
        String user = "admin";
        Connection con = JdbcUtil.getConnection("org.apache.derby.jdbc.ClientDriver", "jdbc:derby://localhost:1527/classpath:myDb", user, "123");
        business(con, user);
        con.close();
    }

    @Test
    public void networkJar2() throws SQLException {
        String user = "admin";
        Connection con = JdbcUtil.getConnection("org.apache.derby.jdbc.ClientDriver", "jdbc:derby://localhost:1527/jar:(d:/temp/my.jar)myDb", user, "123");
        business(con, user);
        con.close();
    }

    @Test
    public void networkServerControl() throws Exception {
        NetworkServerControl server = new NetworkServerControl(InetAddress.getByName("0.0.0.0"), 1527);
        server.start (null);

        CountDownLatch countDownLatch = new CountDownLatch(1);
        new Thread(() -> {
            try {
                //模拟其他应用访问
                networkMemory();
            } catch (Exception e) {
                e.printStackTrace();
            }
            countDownLatch.countDown();
        }).start();

        countDownLatch.await();
        server.shutdown();
    }

    private void business(Connection con, String user) throws SQLException {
        String tableName = "a_student";
        Statement st = con.createStatement();
        String sql = "select 1 from sys.sysTABLES a,sys.sysschemas b where a.schemaid=b.schemaid and upper(b.schemaname)=? and upper(a.tablename)=?";
        PreparedStatement pst = con.prepareStatement(sql);
        pst.setString(1, user.toUpperCase());
        pst.setString(2, tableName.toUpperCase());
        ResultSet rs = pst.executeQuery();
        if (!rs.next()) {//表不存在则创建并初始化数据,这里根据业务需要进行操作
            st.executeUpdate("create table " + tableName + "(id int, name varchar(32))");
            st.executeUpdate("insert into " + tableName + "(id,name) values (1,'李白')");
            st.executeUpdate("insert into " + tableName + "(id,name) values (2,'杜甫')");
        }

        rs = st.executeQuery("select * from " + tableName);
        while (rs.next()) {
            log.info("id={},name={}", rs.getInt("id"), rs.getString("name"));
        }
    }
}
DerbyCae.java
package com.abc.demo.db;

import lombok.extern.slf4j.Slf4j;

import java.sql.*;


@Slf4j
public class JdbcUtil {
    private JdbcUtil() {}

    public static Connection getConnection(String driver, String url, String username, String password) {
        Connection con = null;
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            log.warn("url={},username={},password={}", url, username, password);
            e.printStackTrace();
        }
        return con;
    }
}
JdbcUtil.java

 

标签:jdbc,String,--,数据库,Derby,user,derby,public,con
From: https://www.cnblogs.com/wuyongyin/p/18382227

相关文章

  • Dart学习笔记:语法
    本文更新于2024-12-22,使用Dart2.18.2。目录关键字常量变量基本数据类型数值字符串布尔列表集合映射运算符运算符优先级算数运算符关系运算符类型判定运算符赋值运算符逻辑运算符位运算符条件运算符访问运算符流程控制条件语句if-elseswitch-case循环语句forfor-inwhiledo-whileb......
  • WPF实现加载的动态效果
         思路:1.创建一个画布,长宽100*100;<CanvasWidth="100"Height="100">2.画布上创建一个圆,直径25,位于正上方中间,底色浅灰;<StyleTargetType="Ellipse"><SetterProperty="Width"Value="25"/>......
  • qemu源码解析【03】qom实例
    目录qemu源码解析【03】qom实例1.arm_sbcon_i2c实例qemu源码解析【03】qom实例qemu源码解析【总目录】1.arm_sbcon_i2c实例以hw/i2c/arm_sbcon_i2c.c代码为例,这个实例很简单,只用100行左右的代码,调用qemu系统接口实现了一个i2c硬件模拟先看include/hw/i2c/arm_sb......
  • qemu源码解析【00】qemu-wsl-host环境搭建
    目录qemu源码解析【00】qemu-wsl-host环境搭建2.源码编译和启动qemu3.使用vscode调试wslqemu源码解析【00】qemu-wsl-host环境搭建qemu源码解析【总目录】2.源码编译和启动qemu源码地址:https://gitlab.com/qemu-project/qemu.git根目录:mkdirbuild&cdbuild......
  • Web Worker了解
    WebWorker是什么?WebWorker是浏览器的API,可以创建worker线程,在主线程之外运行JS脚本WebWorker的作用?WebWorker的目的是:为JS创造多线程环境在主线程中创建Worker线程,将耗时的任务分配给Worker线程,Worker线程在后台运行和主线程互不干扰,等到Worker线程执行完毕将计算的结果返......
  • 四种多Agent范式哪种最好?用于对话任务解决的多代理大型语言模型 Multi-Agent Large La
    原文地址摘要在单个大型语言模型多年来主宰人工智能领域的时代,多智能体系统在对话任务解决中崭露头角。此前的研究虽已展现出其在推理任务和创新尝试方面的潜力,但对于其在对话范式方面的局限以及个体智能体的影响,却缺乏分析。多智能体讨论在不同复杂程度任务中的表现怎......
  • 视野修炼第114期 | 2024JS现状调查结果
    欢迎来到第114期的【视野修炼-技术周刊】,下面是本期的精选内容简介......
  • 项目1 Visual Basic 概述
    项目一:VisualBasic概述任务1认识VisualBasic1.项目导入ⅤisualBasic是一种面向对象的程序设计语言,从basic语言发展而来,在WINDOWS环境下运行。Visual:可视的Basic:basic语言2.特点面向对象和事件驱动的设计机制。(1)可视化(2)事件驱动(3)交互式(4)可扩充性3.版本介绍......
  • 例题:从输人框中输人一个学生的信息,包括学号,姓名,语文、数学及英语3科成绩,并输出该学生
    从输人框中输人一个学生的信息,包括学号,姓名,语文、数学及英语3科成绩,并输出该学生的学号,姓名,语文、数学及英语3科成绩,以及总分和平均分(保留两位小数)。程序运行结果如图PrivateSubForm_Click()Dima&,b$,y!,s!,e!Dimtotal#,avg!a=Val(InputBox("请输入学号......
  • 线程池工作原理
    线程池综述它的主要特点为:线程复用;控制最大并发数;管理线程。使用线程池的好处有第一:降低资源消耗。通过重复利用已创建的线程,降低线程创建和销毁带来的资源消耗第二:提高响应速度。当任务到达时,任务可以不需要等到线程创建好就可以立即执行。第三:提高线程的可管理性。线程是稀......