无法使 mysql 连接器 j 工作
我已经设置了类路径环境,但仍然收到错误“Exception:com.mysql.jdbc.Driver”
您知道可能出了什么问题吗?
这是我的测试代码:
import java.sql.*;
public class JdbcExample1 {
public static void main(String args[]) {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql:///test", "root", "secret");
if(!con.isClosed())
System.out.println("Successfully connected to MySQL server...");
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if(con != null)
con.close();
} catch(SQLException e) {}
}
}
}
I've set the classpath envoirenment but still get an error "Exception:com.mysql.jdbc.Driver"
Do you have any idea what might be wrong?
Here is my test code:
import java.sql.*;
public class JdbcExample1 {
public static void main(String args[]) {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql:///test", "root", "secret");
if(!con.isClosed())
System.out.println("Successfully connected to MySQL server...");
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if(con != null)
con.close();
} catch(SQLException e) {}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
很可能不是完整的错误消息。我猜这是一个 ClassNotFoundException,并且您根本没有将 MySQL JDBC 驱动程序作为类路径的一部分。
运行程序时,还需要列出驱动程序
java -cp .;mysql-connector-java-5.1.7-bin.jar JdbcExample1
(这假设 JdbcExample1.class 和 .jar 文件位于当前目录中)
不再需要设置
CLASSPATH
环境变量(实际上从来没有必要)。事实上,它制造的问题多于它解决的问题。使用上面的语法提供驱动程序的路径并运行您的程序
Is most probably not the full error message. I guess it's a ClassNotFoundException and you simply do not have the MySQL JDBC driver as part of your classpath.
When running your program, you need to list the driver as well
java -cp .;mysql-connector-java-5.1.7-bin.jar JdbcExample1
(This assumes JdbcExample1.class and the .jar file are in the current directory)
Setting the
CLASSPATH
environment variable is not necessary anymore (actually it never has been necessary). As a matter of fact it creates more problems than it solves.Use the above syntax to supply the path to your driver and run your program
正如 horse 所说,我很确定这是一个“ClassNotFoundException”。
确保添加“e.printStackTrace();”在你的catch块中。
最好总是获得堆栈跟踪。
As horse says, I'm pretty sure it's a 'ClassNotFoundException'.
To be sure add "e.printStackTrace();" in your catch-block.
Always best to get a stack trace.