⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 database.java

📁 用JAVA实现了,将DB装入内存,内存由DBMS控制,实现简单数据库的创建、数据表的创建、记录插入、查询以及表的删除。
💻 JAVA
字号:
package org.kdb.struct;

import org.kdb.parser.Tokenizer;
import org.kdb.KdbException;

import java.io.File;
import java.io.RandomAccessFile;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;

/**

 * Date: 2007-11-5
 * Time: 10:06:52
 */
public class Database extends DatabaseInfo {
    private Map<String, Table> tables = null;
    private List<User> userList;
    private RandomAccessFile accessChannel = null;
    private File userTableSpace = null;
    private File sysTableSpace = null;

    public Map<String, Table> getTables() {
        return tables;
    }
//
//    public void setSysTableInfo(Map<String,Table> tables) {
//        this.tables = tables;
//    }

//
//    public void setTables(Map<String, Table> tables) {
//        this.tables = tables;
//    }


    public List<User> getUserList() {
        return userList;
    }

    public void setUserList(List<User> userList) {
        this.userList = userList;
    }

    public Table getTable(String tableName) {
        if (isExist(tableName)) {
            return tables.get(tableName);
        }
        return null;
    }

    private boolean isExist(String tableName) {
        return tables != null && tables.containsKey(tableName);
    }


    public void createTable(String tableName, Tokenizer token) {
        if (!isExist(tableName)) {
            if (initTableEnv(tableName)) {
                return;
            }
            Table table = new Table();
            table.setTableName(tableName);
//            List<String> ls = new ArrayList<String>();

            try {
//                token.getName();
//                String s = token.getName();
//                while(!s.equals(")")){
//
//                   s = token.getName();
//                }
                //todo 解析表字段
//                for(String str:ls ){
//                    if(str.equals(",")) continue;
//                    BaseField field = new BaseField();
//                    field.setFieldName(str);
//
//                }
//                for(int i =0;i<ls.size();i++){
//                    BaseField field = new BaseField();
//                    field.setFieldName(ls.get(i));
//                    String str = ls.get(++i);
//
//                }
                String str = token.getName();
                while (!str.equals("(")) {
                    str = token.getName();
                }
                str = token.getName();
                int totalCount = 0;
                while (!str.equals("") && !str.equals(")")) {
                    BaseField field = new BaseField();
                    field.setFieldName(str);
                    str = token.getName();
                    FieldType type = FieldType.getType(str);
                    field.setType(type);
                    str = token.getName();
                    if (str.equals(",") || str.equals(")")) {
                        if (type.equals(FieldType.INT)) {
                            field.setFieldLength(4);
                            totalCount += 4;
                        } else if (type.equals(FieldType.DATE) || type.equals(FieldType.LONG)) {
                            field.setFieldLength(8);
                            totalCount += 8;
                        }
                        table.addFiled(field);
                        str = token.getName();
                        continue;
                    } else {
                        if (type.equals(FieldType.STRING)) {
                            int len = Integer.parseInt(str);
                            field.setFieldLength(len);
                            totalCount += len;
                        }
                    }
                    table.addFiled(field);
                    str = token.getName();
                    if (str.equals(",")) {
                        str = token.getName();
                    }
                }
                table.setTotalFieldCount(totalCount);
                table.setDatabase(this);
            } catch (KdbException e) {
                e.printStackTrace();
            }
            tables.put(tableName, table);
            flush();
        } else {
            System.out.println("该表已经存在!");
            return;

        }

    }

    private boolean initTableEnv(String tableName) {
        File f = new File(userTableSpace, tableName);
        if (f.exists()) {
            System.out.println("该表已经存在");
            return true;
        } else {
            f.mkdirs();
            File tableFile = new File(f, Constant.DEFAULT_TABLE);
            try {
                tableFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {

            }

            return false;
        }
        //检查表空间中是否有该表的目录存在
//        File[] tables = tableSpace.listFiles();
//        tableSpace.
//        for(File f :tables){
//             if()
//        }

    }

    public Database(File file) throws IOException {
        sysTableSpace = new File(file, Constant.DEFAULT_SYS_TABLE_FOLDER);
        userTableSpace = new File(file, Constant.DEFAULT_USER_TABLE_FOLDER);
        File sysTableFile = new File(sysTableSpace, Constant.SYS_TABLE_NAME_PRIFIX);
        setDatabaseName(file.getName());
        tables = new HashMap<String, Table>(20);
        try {
//            File sysFile = new File(file,Constant.SYS_TABLE_NAME_PRIFIX);
            accessChannel = new RandomAccessFile(sysTableFile, "rw");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        loadSystemInfo();
    }

    private void loadSystemInfo() throws IOException {

        accessChannel.seek(0);
        int tableSize = accessChannel.readInt();
        for (int i = 0; i < tableSize; i++) {
            Table sysInfo = new Table();
            sysInfo.setDelete(accessChannel.readByte() == 1);
            int tableNameLen = accessChannel.readInt();
            sysInfo.setTableNameLength(tableNameLen);
            byte[] b = new byte[tableNameLen];
            accessChannel.read(b);
            sysInfo.setTableName(new String(b));
            int fieldCount = accessChannel.readInt();
            int count = 0;
            int totalCount = 0;
            while (count < fieldCount) {
                BaseField field = new BaseField();
                int fieldNameSize = accessChannel.readInt();
//                 field.setFieldLength(fieldSize);
                byte[] fb = new byte[fieldNameSize];
                accessChannel.read(fb);
                String fieldName = new String(fb);
                field.setFieldName(fieldName);   //设置字段名称
                field.setType(FieldType.getType(accessChannel.readByte())); //设置字段的类型
                int fieldSize = accessChannel.readInt();
                field.setFieldLength(fieldSize);//设置这个字段的长度
                sysInfo.addFiled(field);
                count++;
            }
            sysInfo.setTotalFieldCount(totalCount);
            sysInfo.setDatabase(this);

            tables.put(sysInfo.getTableName(), sysInfo);
        }
    }

    private void flush() {
        //todo 将内存中的表信息写入系统表当中
        try {
            int size = tables.size();
            accessChannel.seek(0);
            accessChannel.writeInt(size);
            Iterator<Table> it = tables.values().iterator();
            while (it.hasNext()) {
                Table table = it.next();
                accessChannel.writeByte(0);  //表示该表未被删除
                accessChannel.writeInt(table.getTableNameLength());
                accessChannel.writeBytes(table.getTableName());
                accessChannel.writeInt(table.getBaseFields().size());
                for (BaseField field : table.getBaseFields()) {
                    accessChannel.writeInt(field.getFieldName().length());
                    accessChannel.writeBytes(field.getFieldName());
                    accessChannel.writeByte(field.getType().getIndex());
                    accessChannel.writeInt(field.getFieldLength());
                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public Database(String databaseName) throws IOException {
        this(new File(databaseName));
    }

    public RandomAccessFile getAccessChannel() {
        return accessChannel;
    }

    public void setAccessChannel(RandomAccessFile accessChannel) {
        this.accessChannel = accessChannel;
    }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -