[英]Java and MySQL is not successfully connected
我有一个关于从Eclipse中的Java数据库连接连接到MySQL的问题。 我使用了最新的连接器mysql-connector-java-5.1.30-bin.jar。 另一方面,我在MySQL中的数据库没有密码,因此,如果我输入错了,我决定在用户名“ root”(例如“””)纠正我后将其保留为空。 附件是我的代码和屏幕截图。 请让我知道该怎么办,非常感谢您提供的所有帮助。
<%@ page import="java.sql.*" %><%@ page import="java.io.*" %><%@ page import="com.mysql.*" %><?xml version="1.0"?>
<tours>
<%
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/tours", "root", "");
out.println("connected to database");
}
catch(SQLException e) {
out.println("error connecting to database");
}
%>
</tours>
<%@ page import="java.sql.*" %><%@ page import="java.io.*" %>
<?xml version="1.0"?>
<tours>
<%
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/tours", "root", "");
out.println("connected to database");
}
catch(SQLException e) {
e.printStackTrace(e);
}
%>
</tours>
据我说,没有必要使用newInstance()方法。 可能您应该在mysql上使用密码。 并在catch块中使用e.printStackTrace()方法,以便您可以知道代码出了什么问题。 java.sql。*和com.mysql之间可能存在冲突。 。 使用java.sql。 用于连接到mysql数据库。
1使用printStackTrace检查SQLException,其中应包含更多详细信息。
2确保在mysql db上允许loclhost连接,这取决于特权,有时您可能需要使用您的本地主机IP地址,也可以尝试使用。
我刚刚发现,当您尝试查看结果而不在Eclipse Indigo的内部浏览器上显示xml标记时,只需复制URL(例如localhost:8080 / jsp_final / data.jsp)并将其粘贴到默认的计算机浏览器中(例如Firefox,Chrome,IE,Opera和Safari)。 在那里,您还可以通过右键单击浏览器并选择“查看源代码”来查看来自phpMyAdmin的xml数据源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.