【发布时间】:2015-11-04 04:33:00
【问题描述】:
我正在尝试在 Java 中的连接周围放置 try/catch 块。这是我的代码示例:
public static Connection getConnection() throws Exception, SQLException {
try{
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url = "jdbc:sqlserver://IP\\:Port;databaseName=DB";
String username = "username";
String password = "password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
}catch (SQLException e){
System.out.println(e.getMessage());
}
return conn;
}
我的代码在哪里是我的 * return conn; *!说:conn 无法解析为变量。
我还想在我的 PasswordAuthentication 周围放置 try catch 块,但我尝试的所有方法都对我不起作用。这是我的那部分代码:
class EmailSender{
private Session session;
//Checking for authentication, taking host and port information
private void init(){
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "IP");
props.put("mail.smtp.port", "PORT");
session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
//returning user name and password to connect to email server
return new PasswordAuthentication("Username", "password");
}
});
}
我试图在这部分的整个代码周围放置 try/catch 块,也只是在会话部分周围,但没有什么对我不起作用。谁能帮我解决这个问题?
【问题讨论】:
-
你需要在try catch块之外声明Connection对象,它的作用域是有限的。
标签: java jdbc exception-handling