jdbc中连接对象Con的范围

时间:2011-05-21 08:22:57

标签: java oracle jdbc

*语法错误*

我正在面对我的JDBC问题。 在这一行:

Connection con =DriverManager.getConnection("jdbc:odbc:recordtbl","scott","tiger");

此处出现con错误,我重命名此变量。

这是我的代码:

package md5IntegrityCheck;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;

import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MD5IntegrityCheck
{

  public static void main(String[] args)
    throws UnsupportedEncodingException, NoSuchAlgorithmException
  {


      Statement stmt;
        ResultSet rs;
      Connection con=null;
      PreparedStatement pst=null;
      try
        {
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection con =DriverManager.getConnection("jdbc:odbc:recordtbl","scott","tiger");
                    }
            catch(Exception ee)
            {ee.printStackTrace( );}

          System.out.println("Step 1");
          System.out.println(con.isClosed());

          System.out.println("Enter the filename");
          Scanner scanner = new Scanner(System.in);
          String filename=scanner.nextLine();
          String chksumno="somevalue2";


          // get the file name here and store it in filename variable;
          MD5 md5 = new MD5(filename);
          System.out.println("test");
          chksumno = md5.getHashValue();

          System.out.println("Step 2");
          try{
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  
                con = DriverManager.getConnection("jdbc:odbc:recordtbl","scott","tiger");

                pst=con.prepareStatement("insert into recordtbl values(?,?)");

          //System.out.println(pst.isClosed());
          System.out.println("Step3");
          pst.setString(1,filename);
          System.out.println("Step 4");
          pst.setString(2,chksumno);
          System.out.println("Step 5");
          pst.execute();

          System.out.println("Statement was EXECUTED!");
          con.close( );
          } 


          catch(Exception ee)
            {ee.printStackTrace( );}


    if (args.length <= 0)
    {
      Md5Gui gui = new Md5Gui();
      gui.runGui();
    }
    else
    {
      DoWork runningProgram = new DoWork();
      runningProgram.run(args);
    }
  }
}

1 个答案:

答案 0 :(得分:2)

您已经在尝试第二次声明它的范围内声明了一个名为con的局部变量。这在Java中是不允许的。只需更改它,以便第二次它是一个赋值而不是一个声明:

con = DriverManager.getConnection("jdbc:odbc:recordtbl", "scott", "tiger");

(关于你的代码还有其他各种改变,包括关闭finally块中的连接等,但这应该可以解决你的问题。)