为什么java.sql.DriverManager.getConnection(...)挂起? [英] Why is java.sql.DriverManager.getConnection(...) hanging?

查看:77
本文介绍了为什么java.sql.DriverManager.getConnection(...)挂起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试与大学的MySQL数据库建立连接,但该连接已挂起.

I am attempting to get a connection to my University's MySQL DB but the connection is hanging.

import java.sql.*;

public class ConnectToDB {
        public static void main(String args[]){
                try {
                        Class.forName("com.mysql.jdbc.Driver").newInstance(); 
                        String url = "jdbc:mysql://db.cs.myUniversity.com/dbName"; 
                        System.out.println("BEFORE"); 
                        Connection con = DriverManager.getConnection(url,"me", "password");
                        System.out.println("AFTER");
                        ...

此呼叫:time java ConnectToDB打印(在我最终杀死它之后):

This call: time java ConnectToDB prints (after I eventually kill it):

Copyright 2004, R.G.Baldwin
BEFORE
AFTER

real    3m9.343s
user    0m0.316s
sys     0m0.027s

我刚刚从此处下载了MySQL Connector/J.我不确定这是否是问题的一部分.我非常准确地遵循了指示.

I just downloaded MySQL Connector/J from here. I am not sure if that is part of the problem. I followed the directions fairly precisely.

我也可以像这样在命令行上连接到mysql:

I can also connect to mysql on the command line like this:

$ mysql -u me -h db.cs.myUniversity.com -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 882328
Server version: 5.0.77 Source distribution

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> use dbName;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> SHOW tables;
+-------------------+
| Tables_in_dbName  |
+-------------------+
| classics          | 
+-------------------+
1 row in set (0.00 sec)

可能的问题:

  • 我编写的Java代码
  • 我如何安装MySQL Connector/J
  • 某种网络问题阻止了连接

问题:我应该怎么做才能解决此问题?为什么getConnection呼叫挂起?

Question: What should I do to solve this problem? Why is the getConnection call hanging?

我正在关注本教程

推荐答案

您提供的输出没有帮助.

The output you provide is not helpful.

我看到打印之前和之后,因此建立了连接.该代码未显示这些计时包含的内容,因此我无法确定它们的含义.

I see BEFORE and AFTER being printed, so the connection was made. The code doesn't show what those timings encompass, so I can't tell what they mean.

如果您建议由于从未建立连接而不得不终止代码,则可能是因为您的用户名,密码和客户端IP尚未获得所需的授予权限.

If you're suggesting that your code had to killed because the connection was never made, it's probably because your username, password, and client IP have not been GRANTed permissions that are needed.

可能是:

    您的大学网络;找到网络工程师询问有关防火墙的信息. MySQL数据库中的
  1. 权限;找到DBA并询问.
  2. 您的代码;您发布的内容不足以告诉您.发布全班课程.
  1. your university network; find a network engineer to ask about firewalls.
  2. permission in the MySQL database; find the DBA and ask.
  3. your code; you didn't post enough to tell. Post the whole class.

该版权是怎么回事?我会失去的.

What's up with that copyright? I'd lose that.

此代码有效.对其进行修改,以使相关参数符合您的问题. (我的数据库使用MySQL 5.1.51和一个名为Party的表.)当我在本地计算机上运行它时,挂断时间为641毫秒.

This code works. Modify it so the pertinent parameters match your problem. (Mine uses MySQL 5.1.51 and a table named Party.) When I run it on my local machine, I get a wall time of 641 ms.

package persistence;

import java.sql.*;
import java.util.*;

/**
 * DatabaseUtils
 * User: Michael
 * Date: Aug 17, 2010
 * Time: 7:58:02 PM
 */
public class DatabaseUtils
{
/*
    private static final String DEFAULT_DRIVER = "org.postgresql.Driver";
    private static final String DEFAULT_URL = "jdbc:postgresql://localhost:5432/party";
    private static final String DEFAULT_USERNAME = "pgsuper";
    private static final String DEFAULT_PASSWORD = "pgsuper";
*/
    private static final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
    private static final String DEFAULT_URL = "jdbc:mysql://localhost:3306/party";
    private static final String DEFAULT_USERNAME = "party";
    private static final String DEFAULT_PASSWORD = "party";

    public static void main(String[] args)
    {
        long begTime = System.currentTimeMillis();

        String driver = ((args.length > 0) ? args[0] : DEFAULT_DRIVER);
        String url = ((args.length > 1) ? args[1] : DEFAULT_URL);
        String username = ((args.length > 2) ? args[2] : DEFAULT_USERNAME);
        String password = ((args.length > 3) ? args[3] : DEFAULT_PASSWORD);

        Connection connection = null;

        try
        {
            connection = createConnection(driver, url, username, password);
            DatabaseMetaData meta = connection.getMetaData();
            System.out.println(meta.getDatabaseProductName());
            System.out.println(meta.getDatabaseProductVersion());

            String sqlQuery = "SELECT PERSON_ID, FIRST_NAME, LAST_NAME FROM PERSON ORDER BY LAST_NAME";
            System.out.println("before insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));

            connection.setAutoCommit(false);
            String sqlUpdate = "INSERT INTO PERSON(FIRST_NAME, LAST_NAME) VALUES(?,?)";
            List parameters = Arrays.asList( "Foo", "Bar" );
            int numRowsUpdated = update(connection, sqlUpdate, parameters);
            connection.commit();

            System.out.println("# rows inserted: " + numRowsUpdated);
            System.out.println("after insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));
        }
        catch (Exception e)
        {
            rollback(connection);
            e.printStackTrace();
        }
        finally
        {
            close(connection);
            long endTime = System.currentTimeMillis();
            System.out.println("wall time: " + (endTime - begTime) + " ms");
        }
    }

    public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException
    {
        Class.forName(driver);

        if ((username == null) || (password == null) || (username.trim().length() == 0) || (password.trim().length() == 0))
        {
            return DriverManager.getConnection(url);
        }
        else
        {
            return DriverManager.getConnection(url, username, password);
        }
    }

    public static void close(Connection connection)
    {
        try
        {
            if (connection != null)
            {
                connection.close();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }


    public static void close(Statement st)
    {
        try
        {
            if (st != null)
            {
                st.close();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    public static void close(ResultSet rs)
    {
        try
        {
            if (rs != null)
            {
                rs.close();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    public static void rollback(Connection connection)
    {
        try
        {
            if (connection != null)
            {
                connection.rollback();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    public static List<Map<String, Object>> map(ResultSet rs) throws SQLException
    {
        List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();

        try
        {
            if (rs != null)
            {
                ResultSetMetaData meta = rs.getMetaData();
                int numColumns = meta.getColumnCount();
                while (rs.next())
                {
                    Map<String, Object> row = new HashMap<String, Object>();
                    for (int i = 1; i <= numColumns; ++i)
                    {
                        String name = meta.getColumnName(i);
                        Object value = rs.getObject(i);
                        row.put(name, value);
                    }
                    results.add(row);
                }
            }
        }
        finally
        {
            close(rs);
        }

        return results;
    }

    public static List<Map<String, Object>> query(Connection connection, String sql, List<Object> parameters) throws SQLException
    {
        List<Map<String, Object>> results = null;

        PreparedStatement ps = null;
        ResultSet rs = null;

        try
        {
            ps = connection.prepareStatement(sql);

            int i = 0;
            for (Object parameter : parameters)
            {
                ps.setObject(++i, parameter);
            }

            rs = ps.executeQuery();
            results = map(rs);
        }
        finally
        {
            close(rs);
            close(ps);
        }

        return results;
    }

    public static int update(Connection connection, String sql, List<Object> parameters) throws SQLException
    {
        int numRowsUpdated = 0;

        PreparedStatement ps = null;

        try
        {
            ps = connection.prepareStatement(sql);

            int i = 0;
            for (Object parameter : parameters)
            {
                ps.setObject(++i, parameter);
            }

            numRowsUpdated = ps.executeUpdate();
        }
        finally
        {
            close(ps);
        }

        return numRowsUpdated;
    }
}

这篇关于为什么java.sql.DriverManager.getConnection(...)挂起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆