Java + Firebird connection returning Null

Asked

Viewed 264 times

3

My connection string with the Firebird database returns null.

Follows below code:

public class ModuloConexao {

    public static Connection conector(){
        //criação da varáivel conexao
        Connection conexao = null;

        //chamada do driver do mysql
        String driver = "org.firebirdsql.jdbc.FBDriver";

        //Armazenando informações referente ao banco
        String url = "jdbc:firebirdsql:localhost/3050:C:/Users/Comercial3/Desktop/SMallDATEL/SMALL.FDB"; //alterar para ip de um servidor local...
        String user = "sysdba";
        String password = "masterkey";

        //Estabelecendo conexão com o banco
        try {
            Class.forName(driver);
            conexao = DriverManager.getConnection(url, user, password);
            return conexao;
        } catch (Exception e) {
            //retorno ao usuario final

            return null;
        }

    } 
}

The problem java reports is a Nullpointerexception:

java.lang.Nullpointerexception at br.com.datelcontrole.telas.Telaprincipal.Pesquisarproduto(Telaprincipal.java:212) at br.com.datelcontrole.telas.Telaprincipal$2.keyReleased(Telaprincipal.java:89) at java.awt.Component.processKeyEvent(Unknown Source) javax.swing.Jcomponent.processKeyEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.Keyboardfocusmanager.redispatchEvent(Unknown Source) at java.awt.Defaultkeyboardfocusmanager.dispatchKeyEvent(Unknown Source) at java.awt.Defaultkeyboardfocusmanager.preDispatchKeyEvent(Unknown Source) at java.awt.Defaultkeyboardfocusmanager.typeAheadAssertions(Unknown Source) at java.awt.Defaultkeyboardfocusmanager.dispatchEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.Eventqueue.dispatchEventImpl(Unknown Source) at java.awt.Eventqueue.access$500(Unknown Source) at java.awt.Eventqueue$3.run(Unknown Source) at java.awt.Eventqueue$3.run(Unknown Source) at java.security.Accesscontroller.doPrivileged(Native Method) at java.security.Protectiondomain$Javasecurityaccessimpl.doIntersectionPrivilege(Unknown Source) at java.security.Protectiondomain$Javasecurityaccessimpl.doIntersectionPrivilege(Unknown Source) at java.awt.Eventqueue$4.run(Unknown Source) at java.awt.Eventqueue$4.run(Unknown Source) at java.security.Accesscontroller.doPrivileged(Native Method) at java.security.Protectiondomain$Javasecurityaccessimpl.doIntersectionPrivilege(Unknown Source) at java.awt.Eventqueue.dispatchEvent(Unknown Source) at java.awt.Eventdispatchthread.pumpOneEventForFilters(Unknown Source) at java.awt.Eventdispatchthread.pumpEventsForFilter(Unknown Source) at java.awt.Eventdispatchthread.pumpEventsForHierarchy(Unknown Source) at java.awt.Eventdispatchthread.pumpEvents(Unknown Source) at java.awt.Eventdispatchthread.pumpEvents(Unknown Source) at java.awt.Eventdispatchthread.run(Unknown Source)

Follow my class that makes the mistake:

public class TelaPrincipal extends JFrame {

Connection conexao = null;
PreparedStatement pst = null;
ResultSet rs = null;


private JPanel contentPane;
private JTextField txtCodProd;
private JTable tblProdutos;
private JTextField txtNomeProduto;
private JTextField txtQtdAtual;
private JTextField txtQtdAtualizada;

//txtCodProd = new JTextField(100);

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                TelaPrincipal frame = new TelaPrincipal();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public TelaPrincipal() {
    setTitle("Controle Estoque - DATEL");

    conexao = ModuloConexao.conector();

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 625, 327);
    contentPane = new JPanel();
    contentPane.setBorder(new TitledBorder(null, "Estoque", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    setContentPane(contentPane);





    JLabel lblCdProduto = new JLabel("C\u00F3d. Produto");

    txtCodProd = new JTextField();
    txtCodProd.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent arg0) {
            PesquisarProduto();
        }
    });
    txtCodProd.setColumns(10);

    tblProdutos = new JTable();
    tblProdutos.setModel(new DefaultTableModel(
        new Object[][] {
            {null, null, null},
            {null, null, null},
        },
        new String[] {
            "C\u00F3d.", "Descri\u00E7\u00E3o", "Quantidade Atual"
        }
    ) {
        boolean[] columnEditables = new boolean[] {
            true, false, true
        };
        public boolean isCellEditable(int row, int column) {
            return columnEditables[column];
        }
    });
    tblProdutos.getColumnModel().getColumn(1).setResizable(false);
    tblProdutos.getColumnModel().getColumn(1).setPreferredWidth(349);
    tblProdutos.getColumnModel().getColumn(2).setPreferredWidth(154);

    JLabel lblProduto = new JLabel("Produto");

    txtNomeProduto = new JTextField();
    txtNomeProduto.setEditable(false);
    txtNomeProduto.setColumns(10);

    JLabel lblQuantidadeAtual = new JLabel("Quantidade Atual");

    txtQtdAtual = new JTextField();
    txtQtdAtual.setEditable(false);
    txtQtdAtual.setColumns(10);

    JLabel lblQuantidadeAtualizada = new JLabel("Quantidade atualizada");

    txtQtdAtualizada = new JTextField();
    txtQtdAtualizada.setColumns(10);

    JButton btnAlterar = new JButton("Alterar");

    JButton btnNewButton = new JButton("Cancelar");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
        }
    });

    JLabel lblNewLabel = new JLabel("");
    lblNewLabel.setIcon(new ImageIcon("C:\\Users\\Comercial3\\Desktop\\ERP\\meuCantinho\\src\\br\\com\\meucantinho\\icones\\search.png"));
    GroupLayout gl_contentPane = new GroupLayout(contentPane);
    gl_contentPane.setHorizontalGroup(
        gl_contentPane.createParallelGroup(Alignment.LEADING)
            .addGroup(gl_contentPane.createSequentialGroup()
                .addContainerGap()
                .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
                    .addGroup(gl_contentPane.createSequentialGroup()
                        .addComponent(lblCdProduto)
                        .addPreferredGap(ComponentPlacement.RELATED)
                        .addComponent(txtCodProd, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(ComponentPlacement.RELATED)
                        .addComponent(lblNewLabel))
                    .addGroup(gl_contentPane.createSequentialGroup()
                        .addComponent(lblProduto)
                        .addPreferredGap(ComponentPlacement.RELATED)
                        .addComponent(txtNomeProduto, GroupLayout.PREFERRED_SIZE, 532, GroupLayout.PREFERRED_SIZE))
                    .addGroup(gl_contentPane.createSequentialGroup()
                        .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
                            .addGroup(gl_contentPane.createSequentialGroup()
                                .addComponent(lblQuantidadeAtual)
                                .addPreferredGap(ComponentPlacement.RELATED)
                                .addComponent(txtQtdAtual, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                            .addComponent(btnAlterar, GroupLayout.PREFERRED_SIZE, 215, GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(ComponentPlacement.RELATED, 62, Short.MAX_VALUE)
                        .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
                            .addGroup(gl_contentPane.createSequentialGroup()
                                .addComponent(lblQuantidadeAtualizada)
                                .addPreferredGap(ComponentPlacement.RELATED)
                                .addComponent(txtQtdAtualizada, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                .addGap(3))
                            .addGroup(gl_contentPane.createSequentialGroup()
                                .addComponent(btnNewButton, GroupLayout.PREFERRED_SIZE, 229, GroupLayout.PREFERRED_SIZE)
                                .addGap(27))))
                    .addComponent(tblProdutos, GroupLayout.DEFAULT_SIZE, 577, Short.MAX_VALUE))
                .addContainerGap())
    );
    gl_contentPane.setVerticalGroup(
        gl_contentPane.createParallelGroup(Alignment.LEADING)
            .addGroup(gl_contentPane.createSequentialGroup()
                .addGap(20)
                .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
                    .addComponent(lblCdProduto)
                    .addComponent(txtCodProd, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblNewLabel))
                .addGap(18)
                .addComponent(tblProdutos, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addGap(24)
                .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
                    .addComponent(lblProduto)
                    .addComponent(txtNomeProduto, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addGap(18)
                .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
                    .addComponent(lblQuantidadeAtual)
                    .addComponent(txtQtdAtual, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblQuantidadeAtualizada)
                    .addComponent(txtQtdAtualizada, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addGap(58)
                .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
                    .addComponent(btnAlterar)
                    .addComponent(btnNewButton))
                .addContainerGap(13, Short.MAX_VALUE))
    );
    contentPane.setLayout(gl_contentPane);
}

public void PesquisarProduto(){

    String sql = "SELECT CODIGO, DESCRICAO FROM ESTOQUE WHERE CODIGO = ?";
    try {
        pst = conexao.prepareStatement(sql);
        pst.setString(1, txtCodProd.getText());
        rs = pst.executeQuery();

        tblProdutos.setModel(DbUtils.resultSetToTableModel(rs));

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


}

}

Could you tell me why he’s returning null?

2 answers

3


It is because some error is breaking and the execution falls on the block catch where you simply rule ignore this error and return null.

try {
    Class.forName(driver);
    conexao = DriverManager.getConnection(url, user, password);
    return conexao;
} catch (Exception e) {
    // A variável 'e' tem as informações sobre o erro, por favor, não a ignore.
    return null;
}

I strongly advise you to read these publications:

  • In my debug, the variable 'and' returns this: "java.sql.Sqlnontransientconnectionexception: Connection Rejected: No Connection Character set specified (Property lc_ctype, encoding, charset or localEncoding). Please specify a Connection Character set (eg Property charset=utf-8) or Consult the Jaybird Documentation for more information." Any idea?

  • Bá, brother, I have very little experience with Firebird. You can open a new question with your code and showing this error message, surely someone will be able to help you.

  • @D.Custodio I don’t know if you have found what you were looking for but its url should contain ...SMALL.FDB?charSet=utf-8

  • @Erickmaia Cara...I tried this and it won’t... thanks for the help

  • Have you tried ...SMALL.FDB?encoding=UTF8

  • Yeah...It doesn’t go both ways.

  • @D.Custodio But it is returning null for the reason I said in my reply, young man. You now need to know what is the reason for the error.

  • private Static final String DRIVER = "org.firebirdsql.jdbc.Fbdriver"; private Static final String URL = "jdbc:firebirdsql:192.168.1.158:C:/IBS/Sisfactura/SISFACTURA.FDB? lc_ctype=UNICODE_FSS"; private Static final String USER = "SYSDBA"; private Static final String PASS = "masterkey";

  • @Jonathancr Hein?

  • after . FDB tries this ? lc_ctype=UNICODE_FSS

  • mals nen saw that it was 2 years ago the question.

Show 6 more comments

0

In a test here I was able to simulate this error, and I corrected it like this:

...SMALL.FDB?encoding=ISO8859_1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.