【问题标题】:How to run different sql queries on different threads or as different processes using Java如何使用 Java 在不同的线程上或作为不同的进程运行不同的 sql 查询
【发布时间】:2017-03-06 10:42:57
【问题描述】:

我只想知道如何在单独的线程或单独的进程上运行不同的 SQL 查询。示例:

如果我从 JDBC 发送一个 SQL 查询 (SQL1) 并且运行时间很长,我应该能够发送另一个 SQL 查询 (SQL2),这可能需要更短的时间来完成它的执行。我希望这个查询在单独的线程或进程上运行,这样它就不必等待 SQL1 完成。

【问题讨论】:

    标签: mysql database multithreading jdbc


    【解决方案1】:

    MySQL JDBC 驱动程序 (Connector/J) 是线程保存的。所以你可以启动两个线程在同一个数据库上做不同的事情。只需在每个线程上启动不同的连接。请记住,thread1 上的 SQL 锁可能会阻塞 thread2。

    简单的例子。不要使用老派Class.forName("com.mysql.jdbc.Driver")。 JDBC4 将使用来自连接 URL 的数据为您执行此操作。主线程将启动两个线程并等待两者完成。这两个线程都填充了虚拟查询。

    public class TestThreads {
        public static class Thread1 implements Runnable {
            @Override
            public void run() {
                try {
                    Connection connection = DriverManager
                            .getConnection("jdbc:mysql://localhost/test?"
                                    + "user=myuser&password=mypassword");
    
                    Statement statment = connection.createStatement();
    
                    statment.executeQuery("select * from `table1`");
    
                    [...]
    
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    
        public static class Thread2 implements Runnable {
            @Override
            public void run() {
                try {
                    Connection connection = DriverManager
                            .getConnection("jdbc:mysql://localhost/test?"
                                    + "user=myuser&password=mypassword");
    
                    Statement statment = connection.createStatement();
    
                    statment.executeQuery("select * from `table2`");
    
                    [...]
    
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    
        public static void main(String[] args) {
            Thread thread1 = new Thread(new Thread1());
            Thread thread2 = new Thread(new Thread2());
    
            thread1.start();
            thread2.start();
    
            try {
                thread1.join(1000000);
                thread2.join(1000000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      如果你想要 ResultSet 然后为不同的查询创建不同的线程。执行是一个阻塞过程。所以你必须创建不同的线程来在同一个进程中运行不同的查询。

      【讨论】:

        猜你喜欢
        • 2012-04-05
        • 1970-01-01
        • 2011-11-24
        • 2011-01-07
        • 1970-01-01
        • 2017-01-29
        • 1970-01-01
        • 1970-01-01
        • 2016-05-21
        相关资源
        最近更新 更多