mysql第一次完美连接,第二次返回nullpointer

时间:2013-09-11 13:36:11

标签: java mysql

这是我的连接类/方法:

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,但为什么?

1 个答案:

答案 0 :(得分:0)

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

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

Statement stm = null;