1

这是我的连接类/方法:

static Connection connection = null;
        Statement stm = null;

public static Connection getConexao() {
            try {  
                // Carregando o JDBC Driver padrão  
                String driverName = "com.mysql.jdbc.Driver";                          
                Class.forName(driverName);  
                // Configurando a nossa conexão com um banco de dados//  
                String serverName = "192.168.0.222";    //caminho do servidor do BD  
                String mydatabase ="bd";        //nome do seu banco de dados  
                String url = "jdbc:mysql://" + serverName + "/" + mydatabase;  
                String username = "user";        //nome de um usuário de seu BD        
                String password = "pass";      //sua senha de acesso  
                connection = DriverManager.getConnection(url, username, password);  
                return connection;  
            }  catch (ClassNotFoundException e) {  //Driver não encontrado  
                System.out.println("O driver expecificado nao foi encontrado.");  
                return null;  
            } catch (SQLException e) {  
                //Não conseguindo se conectar ao banco  
                System.out.println("Nao foi possivel conectar ao Banco de Dados.");  
                return null;  
            }  

    }

当 TextField 失去焦点时调用的方法:

private void puxaemailsiscart(String servico) throws SQLException {
                Connection conn = ConectaBD.getConexao();
                Statement stm = null;
                ResultSet results = null;  
                 stm = conn.createStatement ();


                                    try {
                      System.out.println();
                      results = stm.executeQuery ("SELECT * FROM  " + servico + " WHERE protocolo =" + tfProtocolo.getText());
                      if(results.next()) {

                      tfEmailParte.setText(results.getString("Email").toString());


                      } else { 
                          System.out.println("Protocolo nao encontrado");


                      }
                      results.close();
                      stm.close();
                      conn.close();
....

问题是,第一次 TextField 失去焦点时,它可以正常工作并返回数据库结果,但是当我将焦点放在文本字段中并再次失去焦点时,连接返回 null,为什么?因为步骤和第一次一样??

堆栈跟踪

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at telaprincipal$3.puxaemailsiscart(telaprincipal.java:499)
    at telaprincipal$3.focusLost(telaprincipal.java:482)

第 499 行:=Connection conn = ConectaBD.getConexao();说这里是 NullPoint,但是为什么呢?

4

1 回答 1

0

我相信你在我们的类路径上有一个 sqlite 驱动程序,它在第一个周期后以某种方式被加载并试图解析你的 jdbc url。如果您不使用 sqlite,请将其从运行时类路径中删除。

此外,如果您想在每次调用 getConexao() 时打开一个新连接,请不要将连接存储为静态。另外第二个语句似乎是不必要的(并且可能导致意外行为),所以我建议删除:

Statement stm = null;
于 2013-09-12T15:34:34.883 回答