最近在学JSP网页,做到数据库连接那里,一直都出错,后来看了下原来是异常处理语句try...catch的问题,但是不知道为何,请各位帮忙解释一下~~~
代码片段如下:
String strSQLDomain = "localhost"; String strSQLPort = "1433"; String strDatabase = "test"; String strUser = "test"; String strPassword = "test"; Connection conn; //连接数据库 try { String strURL = "jdbc:sqlserver://" + strSQLDomain + ":" + strSQLPort + ";databaseName=" + strDatabase + ";user=" + strUser + ";password=" + strPassword; conn = DriverManager.getConnection ( strURL ); } catch ( Exception e ) { e.printStackTrace(); } conn.close(); //问题就出现在这里了
在Tomcat上调试的时候显示信息:“conn cannot be resolved”,如果我不用异常处理try...catch的话就正常通过
[quote]如果我需要在catch之后插入一段查询代码然后再conn.close()呢[/quote]
[quote]finally{
conn.close();
}
试试[/quote]
总之记得finally{
if(null!=conn){
conn.close()
}
}
应该这样判断一下
if(conn!=null)
conn.close();
catch完用
finally{
conn.close();
}
试试
还有就是你应该要先这样
Connection conn = null;//先赋初值
链接的释放应该要在finally块中执行,毕竟链接是必须要释放的。
Connection conn 没有初始化;
应改变为 Connection conn = null;
因为如果try{}catch{}有异常抛出,conn.close()是非法操作.
建议:
conn.close()应该写在finally中
finally{
conn.close();
}
好处是有异常发生conn也能正常关闭.
如果不写在finally中异常发生了conn 不能正常关闭,浪费资源.
给LZ一个完整的例子,再强调下,finally块中是针对异常来进行的资源释放.代码正常执行完成后,也应该释放资源.
[code="java"]
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBTest {
public static void main(String args[]) {
// 最好申明就初始化,免得不必要的麻烦
Connection con = null;
Statement statement = null;
ResultSet result = null;
try {
// 创建Connection,和LZ的写法类似.
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/studentinfo";
String username = "root";
String password = "admin";
con = DriverManager.getConnection(url, username, password);
// LZ要求执行一段查询
statement = con.createStatement();
// 执行查询,用ResultSet类的对象,返回查询的结果
String query = "select * from student";
result = statement.executeQuery(query);
System.out.println("Student表中的数据如下:");
System.out.println("------------------------");
System.out.println("学号" + " " + "姓名" + " " + "数据成绩 ");
System.out.println("------------------------");
// 对获得的查询结果进行处理,对Result类的对象进行操作
while (result.next()) {
int number = result.getInt("id");
String name = result.getString("name");
String mathScore = result.getString("math");
// 取得数据库中的数据
System.out.println(" " + number + " " + name + " " + mathScore);
}
// 正常关闭结果集,申明和链接.顺序不能错.
result.close();
statement.close();
con.close();
} catch (SQLException ex) {
System.out.println("显示数据库连接错误或查询错误: " + ex.getMessage());
} finally {
// 异常情况下关闭相关资源,避免内存溢出
try {
if (result != null) {
result.close();
}
if (statement != null) {
statement.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
System.out.println("释放资源异常 " + e.getMessage());
}
}
}
}
[/code]
如果我需要在catch之后插入一段查询代码然后再conn.close()呢?
没有问题,
前面定义成这样Connection conn =null;
如果前面有相关操作关闭 Statement和ResultSet再做你的查询操作