java在sybase上创建特定触发器

本文是小小的总结一下本人开发时要在sybase数据库上创建特定的触发器

创建的触发器完成的功能如下

在数据库中指定的表上创建插入,更新,删除触发器,当指定的表发生插入、更新或者删除操作时,将触发触发器相应的动作,触发器的作用就是,将发生上述操作的表的表名、主键名、对应的主键值、相应的操作存到另一张记录表中。本总结中除了创建该类型触发器外还包括删除触发器,删除记录表,判断是否已有记录表。

需要导入的架包:activejdbc.jar,jconn3.jar:

import java.util.List;
import java.util.Map;
import org.javalite.activejdbc.Base;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 模板类
 * @author ywnwa
 *
 */
public abstract class AbstractTriggerManager implements TriggerManager {
    protected static final String TRIGGER_EVENT_TABLE_NAME = "TRIGGER_EVENTS";

    private final Logger          logger                   = LoggerFactory
                                                                   .getLogger(getClass());

    private final String          user;
    private final String          password;

    public AbstractTriggerManager(String user, String password) {
        this.user = user;
        this.password = password;
    }

    public void openDatabase() {
        Base.open(getDriverClass(), getUrl(), this.user, this.password);
        logger.debug("open database sucessfuly!");
    }

    public void closeDatabase() {
        Base.close();
        logger.debug("close database sucessfuly!");
    }

    @SuppressWarnings("rawtypes")
    public boolean hasEventTable() {
        // NOTE (Tan Bingjian)
        // the values of table_name must be given in capital
        List<Map> result = Base.findAll(getSelectTriggerEventTableSql());
        return !result.isEmpty();
    }

    public void createEventTable() {
        if (!hasEventTable()) {
            logger.debug("TRIGGER_EVENTS is not exist! It will be created .");
            Base.exec(getCreateEventTableSql());
            logger.debug("TRIGGER_EVENTS create successfuly!");
        }
        logger.debug("TRIGGER_EVENTS is get ready !");
    }

    public void dropEventTable() {
        if (hasEventTable()) {
            Base.exec(getDropEventTableSql());
            logger.debug("TRIGGER_EVENTS drop successfuly!");
        }
    }

    @Override
    public void create(String name) {
        // trigger for insert
        Base.exec(sqlForTrigger(name, "insert"));
        // trigger for delete
        Base.exec(sqlForTrigger(name, "delete"));
        // trigger for update
        Base.exec(sqlForTrigger(name, "update"));

        logger.debug("The triggers on table " + name
                + " create successfuly ! !");
    }

    @Override
    public void remove(String tableName) {
        String[] actions = getActionsType();// { "INSERT", "UPDATE", "DELETE" };
        for (String i : actions) {
            String triggerName = String.format("TR_%s_%s", tableName, i);
            logger.debug("look for " + triggerName + " on table :" + tableName);
            if (triggerExists(tableName, triggerName)) {
                dropTrigger(triggerName);
                logger.debug("the trigger has been deleted !");
            } else {
                logger.debug("the trigger no existe !");
            }
        }
    }

    @Override
    public void removeAll() {
        List<String> tableNames = getAllTables();
        for (String name : tableNames) {
            remove(name);
        }
    }

    // @Override
    public void removeAll(boolean removeEventTable) {
        removeAll();
        if (removeEventTable && hasEventTable()) {
            dropEventTable();
        }
    }

    @SuppressWarnings("rawtypes")
    public boolean triggerExists(String tableName, String triggerName) {
        List<Map> result = Base.findAll(getSelectTriggersSql(tableName,
                triggerName));
        return !result.isEmpty();
    }

    protected void dropTrigger(String triggerName) {
        Base.exec(getDropTriggerSql(triggerName));
    }

    protected String getEventTableName() {
        return TRIGGER_EVENT_TABLE_NAME;
    }

    protected abstract List<String> getAllTables();

    protected abstract String getDriverClass();

    protected abstract String getUrl();

    protected abstract String getSelectTriggerEventTableSql();

    protected abstract String sqlForTrigger(String tableName, String opType);

    protected abstract String getSelectTriggersSql(String tableName,
            String triggerName);

    protected abstract String getDropTriggerSql(String triggerName);

    protected abstract String getCreateEventTableSql();

    protected abstract String getDropEventTableSql();

    protected abstract String[] getActionsType();
}

这个只是模板类不做过多介绍,下面是具体的实现类:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.javalite.activejdbc.Base;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SyBaseTriggerManager extends AbstractTriggerManager {
    private final Logger        logger                         = LoggerFactory
                                                                       .getLogger(getClass());

    private static final String URL_TEMPLATE                   = "jdbc:sybase:Tds:%s:%s/%s";
    private static final String SELECT_TABLES_SQL_TEMPLATE     = "select name from sysobjects where type=‘U‘";
    private static final String DRIVER_CLASS                   = "com.sybase.jdbc3.jdbc.SybDriver";
    private static final String TRIGGER_EVENT_TABLE_NAME       = "TRIGGER_EVENTS";
    private static final String SELECT_TRIGGER_EVENT_TABLE_SQL = "select name from sysobjects where name=‘"
                                                                       + TRIGGER_EVENT_TABLE_NAME
                                                                       + "‘";
    private static final String CREATE_TRIGGER_EVENT_TABLE_SQL = "CREATE TABLE "
                                                                       + TRIGGER_EVENT_TABLE_NAME
                                                                       + "(TRIGGER_EVENTS_ID INT IDENTITY NOT NULL PRIMARY KEY ,"
                                                                       + " dbName varchar(30),"
                                                                       + " tableName varchar(30),"
                                                                       + " pkNames    varchar(2000),"
                                                                       + " pkValues varchar(2000),"
                                                                       + " action     varchar(20))";
    private static final String SELECT_PK_NAMES_SQL_TEMPLATE   = "select columnname from (SELECT  object_name(id) tabname,  index_col( object_name(id) ,indid,1) columnname  FROM sysindexes  WHERE status & 2048=2048 "
                                                                       + "union "
                                                                       + "SELECT  object_name(id),  index_col( object_name(id) ,indid,2)  FROM sysindexes    WHERE status & 2048=2048 "
                                                                       + "union "
                                                                       + "SELECT  object_name(id),  index_col( object_name(id) ,indid,3)  FROM sysindexes    WHERE status & 2048=2048 "
                                                                       + "union "
                                                                       + "SELECT  object_name(id),  index_col( object_name(id) ,indid,4)  FROM sysindexes    WHERE status & 2048=2048 "
                                                                       + "union "
                                                                       + "SELECT  object_name(id),  index_col( object_name(id) ,indid,5)  FROM sysindexes    WHERE status & 2048=2048 "
                                                                       + "union "
                                                                       + "SELECT  object_name(id),  index_col( object_name(id) ,indid,6)  FROM sysindexes    WHERE status & 2048=2048 "
                                                                       + "union "
                                                                       + "SELECT  object_name(id),  index_col( object_name(id) ,indid,7)  FROM sysindexes    WHERE status & 2048=2048 "
                                                                       + "union "
                                                                       + "SELECT  object_name(id),  index_col( object_name(id) ,indid,8)  FROM sysindexes    WHERE status & 2048=2048 "
                                                                       + "union "
                                                                       + "SELECT  object_name(id),  index_col( object_name(id) ,indid,9)  FROM sysindexes    WHERE status & 2048=2048 "
                                                                       + "union "
                                                                       + "SELECT  object_name(id),  index_col( object_name(id) ,indid,10)  FROM sysindexes    WHERE status & 2048=2048 "
                                                                       + ")pk where  columnname is not null and tabname=‘%s‘";

    private static final String SELECT_TRIGGERS_SQL_TEMPLATE   = "select name from sysobjects  where  type = ‘TR‘and name=‘%s‘";
    private static final String DROP_TRIGGER_SQL_TEMPLATE      = "drop trigger %s";
    private static final String DROP_TRIGGER_EVENT_TABLE_SQL   = "drop table "
                                                                       + TRIGGER_EVENT_TABLE_NAME;
    private final String        url;
    private final String        host;
    private final int           port;
    private final String        db;
    private final String        user;
    private final String        password;

    public SyBaseTriggerManager(String host, int port, String db, String user,
            String password) {
        super(user, password);

        this.db = db;
        this.user = user;
        this.port = port;
        this.host = host;
        this.url = String.format(URL_TEMPLATE, host, port, db);
        this.password = password;
    }

    @SuppressWarnings("rawtypes")
    @Override
    protected List<String> getAllTables() {

        List<Map> result = Base.findAll(SELECT_TABLES_SQL_TEMPLATE);
        List<String> names = new ArrayList<String>();
        for (Map row : result) {
            names.add(row.get("name").toString());
        }

        return names;

    }

    protected String getHost() {
        return host;
    }

    protected int getPort() {
        return port;
    }

    protected String getDb() {
        return db;
    }

    protected String getUser() {
        return user;
    }

    protected String getPassword() {
        return password;
    }

    @Override
    protected String getDriverClass() {

        return DRIVER_CLASS;
    }

    @Override
    protected String getUrl() {

        return url;
    }

    @Override
    protected String getSelectTriggerEventTableSql() {

        return SELECT_TRIGGER_EVENT_TABLE_SQL;
    }

    @Override
    protected String sqlForTrigger(String tableName, String opType) {

        String actionTo;
        String[] pkeys = getPks(tableName);
        String tigger;
        String va = "";
        String declare = "";
        String values = "";
        String pk = "";

        if (opType.equals("insert") || opType.equals("update")) {
            actionTo = "inserted ";
        } else {
            actionTo = "deleted ";
        }
        for (int i = 0; i < pkeys.length; i++) {
            pk += pkeys[i] + ",";
            va += "@" + pkeys[i] + "+" + "‘,‘" + "+";
            declare += "@" + pkeys[i] + " varchar(20)" + ",";
            values += "select " + "@" + pkeys[i] + "=convert(char(200),"
                    + pkeys[i] + ")" + " from " + actionTo;
        }
        declare = declare.substring(0, declare.lastIndexOf(","));
        va = va.substring(0, va.lastIndexOf("+"));
        tigger = "create trigger TR_%s_%s  on %s"
                + " for %s as  declare %s  begin" + " %s  insert into  %s"
                + "(dbName,tableName,pkNames,pkValues,action)"
                + "values(‘%s‘,‘%s‘,‘%s‘,%s,‘%s‘)  end";
        return String.format(tigger, tableName, opType, tableName, opType,
                declare, values, TRIGGER_EVENT_TABLE_NAME, db, tableName, pk,
                va, opType);

    }

    @Override
    protected String getSelectTriggersSql(String tableName, String triggerName) {

        return String.format(SELECT_TRIGGERS_SQL_TEMPLATE, triggerName);
    }

    @Override
    protected String getDropTriggerSql(String triggerName) {

        return String.format(DROP_TRIGGER_SQL_TEMPLATE, triggerName);
    }

    @Override
    protected String getCreateEventTableSql() {

        return CREATE_TRIGGER_EVENT_TABLE_SQL;
    }

    @Override
    protected String getDropEventTableSql() {

        return DROP_TRIGGER_EVENT_TABLE_SQL;
    }

    @SuppressWarnings({ "rawtypes" })
    public String[] getPks(String tableName) {

        ArrayList<Map> list3 = new ArrayList<Map>();
        list3 = (ArrayList<Map>) Base.findAll(String.format(
                SELECT_PK_NAMES_SQL_TEMPLATE, tableName));
        String[] pkNames = new String[list3.size()];

        for (int i = 0; i < list3.size(); i++) {
            Map map = list3.get(i);
            Set set = map.keySet();
            Iterator it = set.iterator();
            while (it.hasNext()) {
                pkNames[i] = (String) map.get(it.next());
                System.out.println(pkNames[i]);

            }
        }

        return pkNames;
    }

    public void create(String tableName) {
        String[] actions = { "insert", "update", "delete" };
        for (String i : actions) {
            String triggerName = String.format("TR_%s_%s", tableName, i);
            if (triggerExists(tableName, triggerName)) {
                dropTrigger(triggerName);
            }
            Base.exec(sqlForTrigger(tableName, i));
        }
        logger.debug("The triggers on table " + tableName
                + " create successfuly ! !");
    }

    @Override
    protected String[] getActionsType() {

        String[] actions = { "insert", "update", "delete" };
        return actions;
    }

}

关键语句介绍:

private static final String SELECT_PK_NAMES_SQL_TEMPLATE

获取对应表的主键名语句,即对应表的主键名,不过这条语句有个局限性是最多只能获取表中只有10个主键的表,超过十个的话第十一个主键将不再获取。如果大家有更加自由的方法欢迎交流。

protected String sqlForTrigger(String tableName, String opType)

该方法返回创建触发器语句

创建触发器语句:return返回的是完整的语句

 tigger = "create trigger TR_%s_%s  on %s"
                + " for %s as  declare %s  begin" + " %s  insert into  %s"
                + "(dbName,tableName,pkNames,pkValues,action)"
                + "values(‘%s‘,‘%s‘,‘%s‘,%s,‘%s‘)  end";
        return String.format(tigger, tableName, opType, tableName, opType,
                declare, values, TRIGGER_EVENT_TABLE_NAME, db, tableName, pk,
                va, opType);

对了,sybase数据库对大小写敏感,还有就是sybase似乎不支持中文创表,和记录中有中午,也许是我还不够了解,懂的朋友欢迎指导

最后,这是第一次写技术博客,就大概贴出了代码,还有很多不足的地方,请大家多多指教,欢迎一起探讨共同进步。

时间: 2024-11-03 05:42:44

java在sybase上创建特定触发器的相关文章

在 Linux 上创建第一个 Service Fabric Java 应用程序

先决条件 开始之前,请安装 Service Fabric SDK.Azure CLI,并在 Linux 开发环境中设置开发群集. 如果使用 Mac OS X,则可使用 Vagrant 在虚拟机中设置 Linux 开发环境. 此外还需配置 Azure CLI 2.0(推荐)或 XPlat CLI,以便部署应用程序. 创建应用程序 Service Fabric 应用程序包含一个或多个服务,每个服务都在提供应用程序功能时具有特定角色. 适用于 Linux 的 Service Fabric SDK 包含

如何在Linux的桌面上创建快捷方式或启动器

如果在Linux桌面系统中你经常使用一个程序,你可能想去创建一个“桌面快捷方式”,以便于你在桌面只要点击一下快捷方式就可以启动它.虽然不少带有图形界面的程序会在安装时自动在桌面上创建快捷方式,还有一些图形界面程序或者命令行程序可能需要你手动创建快捷方式. 在这个教程里,我将告诉你如何在不同的Linux桌面上添加桌面快捷方式.(译注:其实除了作者所述的这些方法外,各种桌面上也还有更简便的方法,大家可以评论分享自己的经验) 一个桌面快捷方式是由内含该APP元信息(例如,app的名字,启动命令或者图标

Java面试题上

1.面向对象的特征有哪些方面?答:面向对象的特征主要有以下几个方面:- 抽象:抽象是将一类对象的共同特征总结出来构造类的过程,包括数据抽象和行为抽象两方面.抽象只关注对象有哪些属性和行为,并不关注这些行为的细节是什么.- 继承:继承是从已有类得到继承信息创建新类的过程.提供继承信息的类被称为父类(超类.基类):得到继承信息的类被称为子类(派生类).继承让变化中的软件系统有了一定的延续性,同时继承也是封装程序中可变因素的重要手段(如果不能理解请阅读阎宏博士的<Java与模式>或<设计模式精

JAVA card 应用开发 创建第一个APPLET

本文讲述在Eclipse环境下,如何创建一个Java卡的项目,新建一个APPLET,运行在Java卡片上. 在建立项目前,必须安装好环境:先下载一个Eclipse,然后安装JCOP即可.(JCOP的下载,需要与NXP签订协议才能拿到安装文件,当然网上可能找到别的版本,这里不讨论).安装次序:安装好Eclipse,然后安装JCOP,然后导入JCOP的授权文件.也可以参考下面这篇文章: 环境搭建:http://blog.csdn.net/menghnhhuan/article/details/761

在窗体上创建自己的光标并输入文字

我们知道在文本框等可以接收输入的组件中,我们可以看到闪烁的光标,并可以输入文字,如果我们在,比如窗体上时,因为不支持输入,也无法显示闪烁的光标,那我们 有办法做自己的输入吗?当然可以,下面我们演示在Form上来输入文字. 用到的API函数如下 GetTextMetrics:获取程序当前的字体信息,存放到TEXTMETRIC结构中 CreateCaret:为系统插入标记创建一个新的形状,并且将插入标记的属主关系指定给特定的窗口.插入标记的形状.可以是线.块或位图 ShowCaret:显示光标 Se

《快速创建网站》2.1 在Azure上创建网站及网站运行机制

现在让我们开始一天的建站之旅. 本文是<快速创建网站>系列的第2篇,如果你还没有看过之前的内容,建议你点击以下目录中的章节先阅读其他内容再回到本文. 1. 网站管理平台WordPress和云计算平台Azure简介2.1 在Azure上创建网站及网站运行机制2.2 域名绑定操作和Azure负载均衡机制2.3 WordPress 初始化和网站管理功能3.1 WordPress 数据导入3.2 WordPress 多站点支持和Azure在线代码编辑器3.3 WordPress 多语言支持 Multi

java中内部类的创建四种情况,三种方式,及内部数据访问权限

内部类和外部类的关系,及内部静态类的数据访问权限,声明方式. 第一种,在外部类内部声明使用内部类,内部类的类型为static和非 static类型,内部类数据类型为private,protected,public 类型的访问权限.外部类为非静态声明和权限如下: package com; public class Test1 { //@author 张春蕾 private class Name{ private int i =1; public int s = 2; protected int m

创建SQL触发器

我们可以对某个数据表添加SQL触发器,当该表进行添加.更新.删除时执行某项操作.不过SQL触发器如果能不用尽量不用,若在项目后期改动程序波及范围太大,使用SQL触发器可以避免,所以才使用. 数据表dbo.User(UserName, Password) CREATE TRIGGER Trigger_User ON dbo.User FOR UPDATE, DELETE AS IF UPDATE(UserName) BEGIN DECLARE @userNameBeforeUpdate NVARC

黑马程序员——Java基础---io(上)

黑马程序员——Java基础---io(上) ------<a href="http://www.itheima.com" target="blank">Java培训.Android培训.iOS培训..Net培训</a>.期待与您交流! ------ 一.概述 Java I/O系统负责处理程序的输入和输出,I/O类库位于java.io包中,它对各种常见的输入流和输出流进行了抽象.如果数据流中最小的数据单元是字节,那么称这种流为字节流:如果数据流