美文网首页
Java SE Demos and Samples 阅读笔记(1

Java SE Demos and Samples 阅读笔记(1

作者: 百炼 | 来源:发表于2016-12-08 20:05 被阅读0次

    说明一下:本人不是参考的Derby官方文档,因为重点是阅读java代码,所以Derby就搜了个博客配置下。另外源码中有readme文件,尽量先看readme,那里面有各个例子从那个方面介绍的,就相当于导航。

    另一个内存数据库的使用 H2数据库使用

    jdk demos & simples样例下载地址

    参考:

    1. Derby的下载安装和使用,(和JAVA中使用Derby)

    环境配置:

    1. java

    变量名:JAVA_HOME
    变量值:C:\Program Files\Java\jdk1.7.0
    变量名:CLASSPATH
    变量值:.;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar;
    变量名:Path
    变量值:%JAVA_HOME%\bin;%JAVA_HOME%\jre\bin;

    2.Derby

    变量名: DERBY_HOME
    变量值: E:\Java\derby\db-derby-10.10.1.1-bin
    在Path加入:%DERBY_HOME%\bin
    在CLASSPATH加入:%DERBY_HOME%\lib \derby.jar;%DERBY_HOME%\lib\derbyclient.jar;%DERBY_HOME%\lib\derbytools.jar;%DERBY_HOME%\lib\derbynet.jar

    Derby常见操作

    windows 进入command,输入ij
    ij> connect ‘jdbc:derby:mydb;create=true’;
    连接mydb数据库:
    ij> connect'jdbc:derby:mytestdb';
    查询数据库等操作,只需要输入相应的Sql语句即可。
    创建一个table:
    ij(CONNECTION1)> create table mytable(id int primary key,name varchar(20));
    插入数据: ij(CONNECTION1)> insert into mytable values(1,'Test');
    断开连接:
    ij> disconnect;
    退出ij:
    ij> exit;

    ** 自动提交命令行**

    1. ij工具自动提交命令行,无需commit
    2. 更改自动提交命令 autocommit on; / autocommit off;

    java操作本地Derby数据库

    1. 本地数据库需使用绝对路径"jdbc:derby:C:\Users\tanzy_000\mydatabase"
    2. 驱动程序 "org.apache.derby.jdbc.EmbeddedDriver"

    window10 系统下 数据库文件默认存放位置
    用户/用户名

    simple阅读

    1. idea新建maven java项目,pom.xml中加入derby的jar包,db-derby-10.13.1.1-bin\demo\programs中simple文件夹拷贝到idea项目中。删除ExampleApp的注释(为了方便阅读,删去了注释,商用请勿这样做,应该加入licence)。


        <dependency>
          <groupId>org.apache.derby</groupId>
          <artifactId>derby</artifactId>
          <version>10.13.1.1</version>
        </dependency>
    

    源码

    建立了一个location表,执行了创建表,往表中插入数据,更新表数据,删除表,建立链接,删除链接等操作。运行结构如下:
    SimpleApp starting in embedded mode
    Connected to and created database derbyDB
    Created table location
    Inserted 1956 Webster
    Inserted 1910 Union
    Updated 1956 Webster to 180 Grand
    Updated 180 Grand to 300 Lakeshore
    Verified the rows
    Dropped table location
    Committed the transaction
    Derby shut down normally
    SimpleApp finished

    package simple;
    
    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 java.util.ArrayList;
    import java.util.Properties;
    
    public class SimpleApp {
        private String framework = "embedded";
        private String protocol = "jdbc:derby:";
    
        public static void main(String[] args) {
            new SimpleApp().go(args);
            System.out.println("SimpleApp finished");
        }
    
        void go(String[] args) {
            parseArguments(args);
    
            System.out.println("SimpleApp starting in " + framework + " mode");
    
            Connection conn = null;
            ArrayList<Statement> statements = new ArrayList<Statement>(); // list of Statements, PreparedStatements
            PreparedStatement psInsert;
            PreparedStatement psUpdate;
            Statement s;
            ResultSet rs = null;
            try {
                Properties props = new Properties(); // connection properties
                props.put("user", "user1");
                props.put("password", "user1");
                String dbName = "derbyDB"; // the name of the database
    
                conn = DriverManager.getConnection(protocol + dbName
                        + ";create=true", props);
    
                System.out.println("Connected to and created database " + dbName);
                conn.setAutoCommit(false);
                s = conn.createStatement();
                statements.add(s);
    
                s.execute("create table location(num int, addr varchar(40))");
                System.out.println("Created table location");
                psInsert = conn.prepareStatement(
                        "insert into location values (?, ?)");
                statements.add(psInsert);
                psInsert.setInt(1, 1956);
                psInsert.setString(2, "Webster St.");
                psInsert.executeUpdate();
                System.out.println("Inserted 1956 Webster");
    
                psInsert.setInt(1, 1910);
                psInsert.setString(2, "Union St.");
                psInsert.executeUpdate();
                System.out.println("Inserted 1910 Union");
    
                psUpdate = conn.prepareStatement(
                        "update location set num=?, addr=? where num=?");
                statements.add(psUpdate);
    
                psUpdate.setInt(1, 180);
                psUpdate.setString(2, "Grand Ave.");
                psUpdate.setInt(3, 1956);
                psUpdate.executeUpdate();
                System.out.println("Updated 1956 Webster to 180 Grand");
    
                psUpdate.setInt(1, 300);
                psUpdate.setString(2, "Lakeshore Ave.");
                psUpdate.setInt(3, 180);
                psUpdate.executeUpdate();
                System.out.println("Updated 180 Grand to 300 Lakeshore");
    
                rs = s.executeQuery(
                        "SELECT num, addr FROM location ORDER BY num");
                int number; // street number retrieved from the database
                boolean failure = false;
                if (!rs.next()) {
                    failure = true;
                    reportFailure("No rows in ResultSet");
                }
    
                if ((number = rs.getInt(1)) != 300) {
                    failure = true;
                    reportFailure(
                            "Wrong row returned, expected num=300, got " + number);
                }
    
                if (!rs.next()) {
                    failure = true;
                    reportFailure("Too few rows");
                }
    
                if ((number = rs.getInt(1)) != 1910) {
                    failure = true;
                    reportFailure(
                            "Wrong row returned, expected num=1910, got " + number);
                }
    
                if (rs.next()) {
                    failure = true;
                    reportFailure("Too many rows");
                }
    
                if (!failure) {
                    System.out.println("Verified the rows");
                }
                // delete the table
                s.execute("drop table location");
                System.out.println("Dropped table location");
    
                conn.commit();
                System.out.println("Committed the transaction");
                if (framework.equals("embedded")) {
                    try {
                        DriverManager.getConnection("jdbc:derby:;shutdown=true");
                    } catch (SQLException se) {
                        if (((se.getErrorCode() == 50000)
                                && ("XJ015".equals(se.getSQLState())))) {
                            System.out.println("Derby shut down normally");
                        } else {
                            System.err.println("Derby did not shut down normally");
                            printSQLException(se);
                        }
                    }
                }
            } catch (SQLException sqle) {
                printSQLException(sqle);
            } finally {
                try {
                    if (rs != null) {
                        rs.close();
                        rs = null;
                    }
                } catch (SQLException sqle) {
                    printSQLException(sqle);
                }
                int i = 0;
                while (!statements.isEmpty()) {
                    // PreparedStatement extend Statement
                    Statement st = (Statement) statements.remove(i);
                    try {
                        if (st != null) {
                            st.close();
                            st = null;
                        }
                    } catch (SQLException sqle) {
                        printSQLException(sqle);
                    }
                }
                try {
                    if (conn != null) {
                        conn.close();
                        conn = null;
                    }
                } catch (SQLException sqle) {
                    printSQLException(sqle);
                }
            }
        }
    
        private void reportFailure(String message) {
            System.err.println("\nData verification failed:");
            System.err.println('\t' + message);
        }
    
        public static void printSQLException(SQLException e) {
            while (e != null) {
                System.err.println("\n----- SQLException -----");
                System.err.println("  SQL State:  " + e.getSQLState());
                System.err.println("  Error Code: " + e.getErrorCode());
                System.err.println("  Message:    " + e.getMessage());
                e = e.getNextException();
            }
        }
    
        private void parseArguments(String[] args) {
            if (args.length > 0) {
                if (args[0].equalsIgnoreCase("derbyclient")) {
                    framework = "derbyclient";
                    protocol = "jdbc:derby://localhost:1527/";
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:Java SE Demos and Samples 阅读笔记(1

          本文链接:https://www.haomeiwen.com/subject/uyismttx.html