我刚刚踏上JSP.我开始编写简单的程序来显示日期,系统信息.然后我尝试连接 MySQL数据库我有一个免费的主机帐户,但我无法连接到MySQL数据库.这是我的代码: %@ page import="java.sql.*" % %@ p
<%@ 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测试了此连接.我哪里弄错了?
原因是驱动程序尚未加载到库中,它没有在连接中实例化,因此连接失败: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); }
Download Driver