简体   繁体   English

使用JDBC连接到数据库的时间

[英]Time of connection to DB using JDBC

When I test the run time like this,the time on my machine is 735 当我像这样测试运行时间时,我的机器上的时间是735

 public class TestDBCP {

    static
    {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
    long l = System.currentTimeMillis();
    Connection conn = null;
    try {
        for(int i =0; i < 100; i++)
        {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcdemo","root","Sph815@cs");
            conn.close();
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(System.currentTimeMillis() - l);
    }

     }

But when I test it using the following its run time becomes longer, i don't understand why more job fewer time? 但是,当我使用以下命令对其进行测试时,它的运行时间会变长,我不明白为什么更多的工作会减少时间?

public class TestDBCP {

static
{
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
public static void main(String[] args) {
long l = System.currentTimeMillis();
    try {
        for(int i =0; i < 100; i++)
        {
 DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcdemo","root","Sph815@cs");
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(System.currentTimeMillis() - l);
    }

}

You're not closing the connection immediately in the second one. 您不会在第二个连接中立即关闭连接。 Opening and closing one connection 100 times won't take nearly as long as opening 100 connections at once. 打开和关闭一个连接100次所需的时间几乎不会与立即打开100个连接所需的时间差不多。

You are assuming that execute an extra statement (the one that close the connection) will implies that the program will take more time because the close() statement execution adds extra CPU usage. 您假设执行一条额外的语句(关闭连接的一条语句)将意味着该程序将花费更多时间,因为执行close()语句会增加CPU使用率。

If you doesn't execute it, you save this CPU time, however the database has to deal with more open connections simultaneously , which can degrade his performance. 如果不执行它,则可以节省CPU时间,但是数据库必须同时处理更多打开的连接 ,这可能会降低其性能。 Therefore, the getConnection() statement will takes longer to execute as the number of open connections increases. 因此,随着打开的连接数的增加,getConnection()语句将花费更长的时间执行。

Probably this is the reason your second version execute slower than the first one. 这可能是第二个版本执行速度比第一个版本慢的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM