java简单从一个数据库获取数据,然后插入到另外一个数据库

本文介绍了一种在SpringBoot环境下实现从一个数据库获取数据并插入到另一个数据库的方法,涉及了多数据源配置和时间条件判断。示例代码展示了如何处理MySQL与Oracle之间的数据交换,并强调了对SQL语句的调试和程序化处理。此外,还提供了一个简单的实体类用于数据传输。整个过程旨在简化数据库操作,提高程序的灵活性。
摘要由CSDN通过智能技术生成

思路:从一个数据库获取数据,然后插入到另外一个数据库,使用springboot的话就需要在application.yml配置两个数据库,这样比较麻烦也要注意注解的使用,如:

server:
  port: 7101
spring:
  jpa:
    show-sql: true
  datasource:
    test1:
      driver-class-name: org.postgresql.Driver
      jdbc-url: jdbc:postgresql://127.0.0.1:5432/test  #测试数据库
      username: root
      password: root

    test2:
      driver-class-name: oracle.jdbc.driver.OracleDriver
      jdbc-url: jdbc:oracle:thin:@127.0.0.1:8888:orcl  #测试数据库
      username: root
      password: root

但是我们可以通过简单程序实现然后打成jar包就可以很方便在我们的程序中使用。
下面我们就来展示一下这个简单程序:
首先是依赖注入(当然也可以使用mysql的jar包)

<!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

然后就是代码:
注意:sql语句可以先在数据库中调试,成功就在代码中运行,如果对于sql不熟悉的话可以看笔者往期的数据库文章学习,代码中的时间是因为笔者需要在8点和17点这两个时间段定时发送数据。代码中有详细的注解,有不明白的地方可以问笔者。

public class Exchagedate {

    public static void main(String[] args) throws Exception {
        Connection con = null;// 创建一个数据库连接
        Statement stm = null;
        ResultSet result = null;// 创建一个结果集对象
        //获取系统当前时间
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        //将当前时间转换成yyyy-MM-dd HH:mm:ss格式
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取前一天的时间
        Timestamp currentTime1 = new Timestamp(System.currentTimeMillis()-24 * 60 * 60 * 1000);
        //将时间转换成yyyy-MM-dd格式
        SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");
        String dateString1 = formatter2.format(currentTime1);
        String dateString2 = formatter2.format(currentTime);
        Calendar calendar = Calendar.getInstance();

        String startTimeStr = formatter.format(currentTime1);
        try {
            //开始连接数据库
            System.out.println("开始尝试连接cailiandb数据库!");
            String url = "jdbc:mysql://10.*.*.*:3306/cailiandb";
            String user = "root";// 用户名,系统默认的账户名
            String password = "*019";// 你安装时选设置的密码
            con = DriverManager.getConnection(url, user, password);// 获取连接
            System.out.println("cailiandb连接成功!");
            String sql = null;
            //判断当前时间是否大于12点,如果大于12点,就取早上8点到下午17点的数据
            // 如果小于12点就取昨天下午17点到今天上午8点的数据
            if(calendar.get(Calendar.HOUR_OF_DAY) > 12){
                sql = "select * from article between '"+dateString2+" 8:00:00' and '"+dateString2+" 17:00:00'  order by a.id desc;" ;// 预编译语句,“?”代表参数

            }else {
                sql = "select *from article between '"+dateString1+" 17:00:00' and '"+dateString2+" 8:00:00'  order by a.id desc;" ;// 预编译语句,“?”代表参数
            }
            stm=con.createStatement();
            result=stm.executeQuery(sql);
            List<Article> articles = new ArrayList<>();
            while (result.next()){
                Article article = new Article();
               //需要接收的字段
                article.setId(result.getString("id"));
                article.setTitle(result.getString("title"));
                article.setTime(result.getString("from_unixtime(a.modified_time)"));
                article.setSource(result.getString("name") ==null?"":result.getString("name"));
                article.setContent(result.getString("content"));
                articles.add(article);
            }
            ExportData(articles);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 逐一将上面的几个对象关闭,因为不关闭的话会影响性能、并且占用资源
                // 注意关闭的顺序,最后使用的最先关闭
                if (result != null)
                    result.close();
                if (stm != null)
                    stm.close();
                if (con != null)
                    con.close();
                System.out.println("cms数据库连接已关闭!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public static String ExportData(List<Article> articles) {

        Connection con = null;// 创建一个数据库连接
        Statement stm = null;
        //获取当前时间
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        try {
            System.out.println("开始尝试连接gf_new数据库!");
            //本地测试数据库
            String url = "jdbc:mysql://127.0.0.1:3306/company?characterEncoding=utf-8";
            String user = "root";// 用户名,系统默认的账户名
            String password = "root";//
            con = DriverManager.getConnection(url, user, password);// 获取连接
            stm=con.createStatement();
            System.out.println("gf_new连接成功!");
            //进行for循环遍历,通过title的内容将重复的title去除掉
            for (int i = 1; i < articles.size(); i++) {
                if (!articles.get(i-1).getTitle().equals(articles.get(i).getTitle())){
                    System.out.println(articles.get(i));
                    //插入数据
                    String sql = "insert into COMPANY_BUSINESS_NEWS(ID,TITLE,COMPCODE,SCORE,IMPORTANCE,INDICCODE2,EMOTION,SOURCE,CONTENT,URL,LINK,BUSINESS_TAG,SECURITIES_TAG,PUBLISH_TIME,CREATE_TIME,G_UPDATE_TIME, importance_input" +
                            ") " +
                            "values('"
                            +articles.get(i-1).getId()+Integer.toString(i*i)
                            +"','"
                            +articles.get(i-1).getTitle()
                            +"',NULL,NULL,NULL,NULL,NULL,'"+articles.get(i-1).getSource()+"','"+articles.get(i-1).getContent()+"','',''," +
                            "NULL,NULL,'"+articles.get(i-1).getTime()+"','"+dateString+"','"+dateString+"',NULL) ;";
                    System.out.println(sql);
                    stm.executeUpdate(sql);
                }

            }
            System.out.println("ok");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (stm != null)
                    stm.close();
                if (con != null)
                    con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

在实现前还需要提供一个实体类方便接收数据

public class Article {
    private String id;
    private String title;
    private String time;
    private String source;
    private String content;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    @Override
    public String toString() {
        return "Article{" +
                "id='" + id + '\'' +
                ", title='" + title + '\'' +
                ", time='" + time + '\'' +
                ", source='" + source + '\'' +
                ", content='" + content + '\'' +
                '}';
    }
}

今天的分享到此为止,谢谢各位看官。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值