Java的JDBC访问Mysql的一个问题,在最后的conn.close();为什么会报错?

来源:百度知道 编辑:UC知道 时间:2024/09/21 22:34:11
import java.sql.*;

public class JDBCExample1 {
public static void main(String[] args) {
String connectionURL =
"jdbc:mysql://localhost:3306/test?user=root&password?characterEncoding=GBK";

try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(connectionURL);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select id,msg from echo_message");
while (rs.next()) {
System.out.println(rs.getString("id") + "\n" +
rs.getString("msg"));
}

}catch(SQLException e)
{
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();<

楼上二位加起来才是正解
首先conn被声明成了一个局部变量,只有在try的代码段里有效,到finally里这个变量就无效了
我想你提示的错误应该是找不到符号吧?
其次,conn.cloes()方法本身会抛出异常,所以需要对其进行异常处理

conn.close(); 本身这句话就有可能会有异常抛出,需要改成:
finally{
try{

conn.close();

}catch(SQLException e)
{

e.printStackTrace();
}

}

以后说错,也应该把错误贴出来,这样节约回答者的时间

赶紧结贴,说的非常明白了。

试试在try前面声明Connection conn = null;