Java - JDBC驱动程序和MySQL数据库连接问题

时间:2010-06-18 22:51:54

标签: java mysql database jdbc

好的 - 我找到了数据库附带的驱动程序版本..但现在我得到以下内容。

  

有例外!通讯链接   由于潜在的异常导致的失败:

     

**开始没有异常**

     

java.net.ConnectException消息:   连接超时:连接

     

堆栈跟踪:

     

java.net.ConnectException:Connection   超时:连接           在java.net.PlainSocketImpl.socketConnect(Native   方法)           在java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)           在java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)           在java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)           在java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)           在java.net.Socket.connect(Socket.java:525)           在java.net.Socket.connect(Socket.java:475)           在java.net.Socket。(Socket.java:372)           在java.net.Socket。(Socket.java:215)           在com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)           在com.mysql.jdbc.MysqlIO。(MysqlIO.java:271)           在com.mysql.jdbc.Connection.createNewIO(Connection.java:2771)           在com.mysql.jdbc.Connection。(Connection.java:1555)           在com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)           在java.sql.DriverManager.getConnection(DriverManager.java:582)           在java.sql.DriverManager.getConnection(DriverManager.java:185)           at freelancebillingapp.customerInfoUI.jButton1MouseClicked(customerInfoUI.java:221)           at freelancebillingapp.customerInfoUI.access $ 000(customerInfoUI.java:12)           at freelancebillingapp.customerInfoUI $ 1.mouseClicked(customerInfoUI.java:59)           在java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:253)           at java.awt.Component.processMouseEvent(Component.java:6266)           在javax.swing.JComponent.processMouseEvent(JComponent.java:3255)           at java.awt.Component.processEvent(Component.java:6028)           at java.awt.Container.processEvent(Container.java:2041)           at java.awt.Component.dispatchEventImpl(Component.java:4630)           at java.awt.Container.dispatchEventImpl(Container.java:2099)           at java.awt.Component.dispatchEvent(Component.java:4460)           at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)           at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4247)           at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)           at java.awt.Container.dispatchEventImpl(Container.java:2085)           at java.awt.Window.dispatchEventImpl(Window.java:2475)           at java.awt.Component.dispatchEvent(Component.java:4460)           at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)           at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)           at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)           at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)           at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)           at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)           在java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

     

**结束了例外**

     

发送到服务器的最后一个数据包是1   ms前。

3 个答案:

答案 0 :(得分:3)

This可能无法解决,但它会告诉您其他人遇到此问题。

确保您拥有与您的MySQL版本匹配的JDBC驱动程序的精确版本。

我强烈建议你更改这样的代码。您根本没有正确关闭资源。

根据您自己的需要进行调整。我在我的机器上创建了一个本地MySQL数据库并添加了一个客户表。它运作得很好。

package persistence;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class DatabaseUtils
{
    private static final String URL = "jdbc:mysql://localhost:3306/contacts";
    private static final String USERNAME = "contacts";
    private static final String PASSWORD = "contacts";

    public static final String SELECT_SQL = "select customer_id, name, street, city, state, zip, phone, url from customer order by customer_id";
    public static final String INSERT_SQL = "insert into customer(name, street, city, state, zip, phone, url) values(?,?,?,?,?,?,?)";

    public static void main(String[] args)
    {
        Connection connection = null;

        try
        {
            connection = getConnection(URL, USERNAME, PASSWORD);
            List<Map> rows = findAllCustomers(connection);

            for (Map row : rows)
            {
                System.out.println(row);                    
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        finally
        {
            close(connection);
        }
    }

    public static List<Map> findAllCustomers(Connection connection) throws SQLException
    {
        List<Map> rows = new ArrayList<Map>();
        PreparedStatement st = null;
        ResultSet rs = null;

        try
        {
            st = connection.prepareStatement(SELECT_SQL);
            rs = st.executeQuery();
            while (rs.next())
            {
                rows.add(map(rs));                
            }
        }
        finally
        {
            close(rs);
            close(st);
        }

        return rows;
    }

    private static Map<String, Object> map(ResultSet rs) throws SQLException
    {
        Map<String, Object> row = new LinkedHashMap<String, Object>();

        ResultSetMetaData meta = rs.getMetaData();

        int numColumns = meta.getColumnCount();
        for (int i = 1; i <= numColumns; ++i)
        {
            String column = meta.getColumnName(i);
            Object value = rs.getObject(i);
            row.put(column, value);
        }

        return row;
    }

    public static Connection getConnection(String url, String username, String password) throws SQLException
    {
        Driver driver = DriverManager.getDriver(url);

        DriverManager.registerDriver(driver);

        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 void rollback(Connection connection)
    {
        try
        {
            if (connection != null)
            {
                connection.rollback();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }
}

答案 1 :(得分:0)

mysql可以接受网络连接吗?当您使用“mysql”命令行程序连接时,您没有进行网络连接,但是当您使用JDBC时,您正在建立网络连接。尝试在mysql命令行中使用“-h localhost”来查看。

答案 2 :(得分:0)

            /*
             Connection
             */


            import com.mysql.jdbc.Connection;
            import java.sql.DriverManager;


            public class PersonalConnection {

                private String url = "jdbc:mysql://localhost:3306/";
                private String schema = "database name";
                private String uname = "";
                private String password = "";
                private Connection connection;

                public Connection openConnection() {
                    try {
                        try {
                            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
                        } catch (Exception ex) {
                        }
                        connection = (Connection) DriverManager.getConnection(url + schema, uname, password);
                    } catch (Exception ex) {
                    }
                    return connection;
                }

                public void closeConneciton() {
                    try {
                        connection.close();
                    } catch (Exception ex) {
                    }

                }
            }

        /* Servlet */



          response.setContentType("text/html;charset=UTF-8");
                    PrintWriter out = response.getWriter();
                    DetailsBean db = new DetailsBean();

                    String name = request.getParameter("name");
                    String countryname = request.getParameter("countryname");
                    String statename = request.getParameter("statename");

                    db.setName(name);
                    db.setCountry(countryname);
                    db.setState(statename);

                    DetailsManager dm = new DetailsManager();
                    String result = dm.insertDetailsManager(db);
                    if (result.equals("true")) {
                       /* RequestDispatcher rd = request.getRequestDispatcher("StateDetails.jsp?name=" + db.getName());
                        rd.forward(request, response);*/
                        response.sendRedirect("StateDetails.jsp");
                    } else {
                        out.print(result);
                    }

        /*  DAO */



        /*
         * To change this template, choose Tools | Templates
         * and open the template in the editor.
         */


        import com.mysql.jdbc.Connection;
        import java.sql.PreparedStatement;


        import java.sql.ResultSet;


        public class DetailsDAO {

            private Connection connection;
            private PersonalConnection con;

            public DetailsDAO() {
                con = new PersonalConnection();
            }

            public String insertRecordDAO(DetailsBean db) {

                int rowcount=0;
                try {
                    connection=con.openConnection();
                    String query = "INSERT INTO personal_details(user_name,country_name,state_name) values(?,?,?);";
                    PreparedStatement ps = connection.prepareStatement(query);
                    ps.setString(1, db.getName());
                    ps.setString(2, db.getCountry());
                    ps.setString(3, db.getState());
                    rowcount = ps.executeUpdate();
                    if(rowcount==1)
                    {
                        return "true";
                    }
                    else
                    {
                        return "false";
                    }
                } catch (Exception ex) {
                    return ex+"";

                } finally {
                    con.closeConneciton();
                }
            }

            public ResultSet getGetails() throws Exception
            {
                connection=con.openConnection();
                String query="SELECT * from state_details";
                PreparedStatement ps=connection.prepareStatement(query);
                ResultSet rs=ps.executeQuery();
                return rs;
            }
        }

    /*Manager*/

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */

    import java.util.ArrayList;


    public class DetailsManager {

        DetailsDAO detdao = new DetailsDAO();

        public String insertDetailsManager(DetailsBean db) {
            String rowcount = detdao.insertRecordDAO(db);
            return rowcount;
        }



    }

/*Bean*/


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



public class DetailsBean {

    private String name;
    private String country;
    private String state;

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }


}