We often use exception handling try catch when using JDBC, as in my example below:
public static Connetion getConnection(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
}catch(SQLException e){
e.printStackTrace();
}
return conn; //返回不了conn的值,因为conn的作用域只在try后面的{}块中,跳出try后面{}就失效了。
}
To return the value of conn, the correct way to write it is to write the declaration of conn before try:
public static Connetion getConnection(){
Connection conn = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
}catch(SQLException e){
e.printStackTrace();
}
return conn;
}