我只是涉足JSP。我开始编写简单的程序来显示日期和系统信息。然后,我尝试连接一个MySQL database我有一个免费托管帐户的帐户,但是无法连接到MySQL数据库。这是我的代码:
MySQL database
<%@ page import="java.sql.*" %> <%@ page import="java.io.*" %> <html> <head> <title>Connection with mysql database</title> </head> <body> <h1>Connection status</h1> <% try { String connectionURL = "jdbc:mysql://mysql2.000webhost.com/a3932573_product"; Connection connection = null; Class.forName("com.mysql.jdbc.Driver").newInstance(); connection = DriverManager.getConnection(connectionURL, "a3932573_dibya", "******"); if(!connection.isClosed()) out.println("Successfully connected to " + "MySQL server using TCP/IP..."); connection.close(); }catch(Exception ex){ out.println("Unable to connect to database."); } %> </font> </body> </html>
我收到“ 连接状态无法连接到数据库”消息 。我已经PHP使用相同的用户名,密码和数据库名称测试了此连接。我在哪里犯错?
PHP
原因是驱动程序尚未加载到库中,它没有在连接中实例化,因此连接失败:
try { String connectionURL = "jdbc:mysql://host/db"; Connection connection = null; Class.forName("com.mysql.jdbc.Driver").newInstance(); connection = DriverManager.getConnection(connectionURL, "username", "password"); if(!connection.isClosed()) out.println("Successfully connected to " + "MySQL server using TCP/IP..."); connection.close(); }catch(Exception ex){ out.println("Unable to connect to database"+ex); }
下载驱动