以下程序没有抛出任何异常,可就是输出con is null 这是什么情况啊?

import java.sql.*;

public class DBConnection {

private static Connection con;

public static Connection getMySQLConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/ray", "root", "root");
}
catch(ClassNotFoundException e) {
System.out.println("Sorry, you get a ClassNotFoundException");
}
catch(SQLException e) {
System.out.println("Sorry, you get a SQLException");
}
if (con == null) {
System.out.println("con is null");
}
return con;
}
}

哈士奇WWW
浏览 572回答 2
2回答

人到中年有点甜

private static Connection con; 这里定义了一个conpublic static Connection getMySQLConnection() {try {Class.forName("com.mysql.jdbc.Driver");这里又定义了一个con,它在try的范围内有效,出了try就没效了。Connection con = DriverManager.getConnection("jdbc:mysql://localhost/ray", "root", "root");

陪伴而非守候

private static Connection con;Connection con = 。。。重新声明了。里面的 con = ..
打开App,查看更多内容
随时随地看视频慕课网APP