读书人

运用语句对象statement时候 connectio

发布时间: 2013-02-18 10:50:49 作者: rapoo

使用语句对象statement时候 connection必须在try外先null
在做连接数据库删除用户信息时候有一个问题
————————————————————————————————
<%
String url="jdbc:mysql://localhost:3306/javaweb";
String user="root";
String password="123456";

try{
Class.forName("com.mysql.jdbc.Driver");

Connection conn=DriverManager.getConnection(url,user,password);}
catch(ClassNotFoundException e){
out.println("未找到驱动");}
catch(SQLException e){
out.println("连接数据库失败");}
try{
Statement stmt =conn.createStatement();
String deleteUser="DELETE FROM user WHERE userid=2";
stmt.executeUpdate(deleteUser);}
catch(SQLException e){
out.println("删除用户信息失败");}
%>
————————————————————————————————
在new 语句对象statement stmt的时候提示 conn cannot be resolved,
我知道怎么改,即要在第一个try外new conn=null既Connection conn=null;
————————————————————————————————
但是我想知道为什么?在做连接数据库操作的时候,在里面new是可以的,但是
为什么执行语句对象statement的时候conn就cannot be resolved了?为什么?
是因为try么? jdbc
[解决办法]


try{
// load driver
Class.forName("com.mysql.jdbc.Driver");
// get database connection
Connection conn=DriverManager.getConnection(url,user,password);}
// stmt execute sql
Statement stmt =conn.createStatement();
String deleteUser="DELETE FROM user WHERE userid=2";
stmt.executeUpdate(deleteUser);}

catch(ClassNotFoundException e){
out.println("未找到驱动")}
catch(SQLException e){
out.println("连接数据库失败");}


try{
这里的conn在第一个try的{},你可以理解为所第一个try的局部变量
Connection conn = DriverManager.getConnection
}

try{
Statement stmt : 怎么可能找到另外一个代码块的局部变量来调用呢?
}

如果定义在外面,那是全局变量,大家都可以访问的
[解决办法]
引用:
Java code?1234567891011121314 try{ // load driver Class.forName("com.mysql.jdbc.Driver"); // get database connection Connection conn=DriverManager.getConnection(url,user……

1楼正解,主要是变量的作用域的范围。

读书人网 >Java Web开发

热点推荐