Galera ajuda aqui o que falta para inserir os dados

9 respostas
G

Tipo quando tento cadastrar da a mensagem abaixo no netbeans.

run:
Driver JDBC carregado
Erro na conexão ao Bando de Dados : Resource Exception. operating system directive CreateFile failed
null
Reason: operating system directive CreateFile failed
null

Abaixo ta o meu arquivo de conexão com o banco e o de cadastro.

package classes;



public interface DataBaseConstantes {
	public final static String DRV = "org.firebirdsql.jdbc.FBDriver";

	public final static String URL2 = "jdbc:firebirdsql://localhost/" + "c:/banco/auto.gdb";
         //"jdbc:firebirdsql:localhost/3050:c:/banco/auto.gdb";                           
        public final static String USUARIO = "SYSDBA";
	public final static String SENHA = "masterkey";
         
}
package telas;
import classes.DataBaseConstantes;
import javax.swing.*;
import java.sql.*;
/**
 *
 * @author 19902003
 */
public class TelaCadastro extends javax.swing.JFrame implements DataBaseConstantes{
    
    public static Connection con = null;

    public TelaCadastro() {
        initComponents();
    }

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        String driver = null;
        // TODO add your handling code here:
                try {
			/* Instanciando a classe do driver através do seu nome */
			Class.forName( DRV );
			System.out.println( "Driver JDBC carregado" );
		} catch ( ClassNotFoundException cnfe ) {
			System.out.println( "Driver JDBC não encontrado : " +
							   cnfe.getMessage() );
		}

		/* Criando conexão com o banco de dados */
		try {
			/* Obtendo a conexão com o banco de dados */
			con = DriverManager.getConnection(URL2, USUARIO, SENHA);
			System.out.println( "Conexão com o banco de dados estabelecida." );
		} catch ( SQLException sqle ) {
			System.out.println( "Erro na conexão ao Bando de Dados : " +
							            sqle.getMessage() );
		}
		
          try{


         String sql = null;
     
              sql = "INSERT INTO AUTOMOVEL(codigo,marca) VALUES (?,?)";
              PreparedStatement ps = con.prepareStatement(sql);
              String codigo = jTextField1.getText();
              String marca = jTextField5.getText();
              ps.setString(1,codigo);
              ps.setString(2,marca);

              ps.executeUpdate();
    
    	
    	} catch ( SQLException sqle ) {
			System.out.println( "Erro na conexão ao Bando de Dados : " +
							            sqle.getMessage() );
		}	
	


	/* fechando a conexão com o SGBD */
		try {
			con.close();
			JOptionPane.showMessageDialog(null, "Dados Inseridos com sucesso");
			jTextField1.setText("");
			jTextField2.setText("");
			
			
			//System.out.println( "Conexão com o banco de dados fechada" );
		} catch ( SQLException sqle ) {
			System.out.println( "Erro no fechamento da conexão : " );
		}
    }                                        

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TelaCadastro().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;

9 Respostas

lucascaton

Está sendo exibida essa sua mensagem avisando que que conectou corretamente no banco?

G

Aparece apenas a mensagem abaixo.

Driver JDBC carregado
Erro na conexão ao Bando de Dados : Resource Exception. operating system directive CreateFile failed
null
Reason: operating system directive CreateFile failed
null

L

colega…

vc nao colocou a porta para conexao no sua url!

jdbc:firebirdsql:ip_do_servidor/3050:/caminho_do_bco_de_dados.gdb

se nao for isso, procure olhar se o caminho eh realmente aquele que voce colocou. se o caminho estiver certo repare se letras maiusculas estao maiusculas e vice-versa tipo a letra do drive ao inves de c coloque C ou o nome do banco de dados…
ja tive problemas com o firebird assim… coloquei o nome do banco minusculo sendo que estava em maiusculo… mas isso foi fora do java. talvez algo parecido com isso pode acontecer dentro do java tb na hora de acessar o banco!

Ah sim… procure colocar tb 127.0.0.1 ao inves de localhost…

lucascaton

É bem provável que seja por causa da porta…

Faz o teste aí e diga se conseguiu. :wink:

G

o Arquivo ta no caminho c:\banco\auto.gdb

coloquei a porta na URL a mostra outro erro.

public final static String url = "jdbc:firebirdsql:localhost/3050:/c:/banco/auto.GDB";

Ta mostrando o erro abaixo agora.

Driver JDBC carregado
Erro na conexão ao Bando de Dados : Resource Exception. Unable to complete network request to host “stephan-PC”.
Failed to locate host machine.
Undefined service c/tcp.
Reason: Unable to complete network request to host “stephan-PC”.
Failed to locate host machine.
Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException
Undefined service c/tcp.

lucascaton

Na documentação quem acompanha o driver JDBC do FireBird, encontrei o seguinte exemplo:

// Original version of this file was part of InterClient 2.01 examples
//
// Copyright InterBase Software Corporation, 1998.
// Written by com.inprise.interbase.interclient.r&d.PaulOstler :-)
//
// Code was modified by Roman Rokytskyy to show that Firebird JCA-JDBC driver
// does not introduce additional complexity in normal driver usage scenario.
//
// An example of using a JDBC 2 Standard Extension DataSource.
// The DataSource facility provides an alternative to the JDBC DriverManager,
// essentially duplicating all of the driver manager?s useful functionality.
// Although, both mechanisms may be used by the same application if desired,
// JavaSoft encourages developers to regard the DriverManager as a legacy
// feature of the JDBC API.
// Applications should use the DataSource API whenever possible.
// A JDBC implementation that is accessed via the DataSource API is not
// automatically registered with the DriverManager.
// The DriverManager, Driver, and DriverPropertyInfo interfaces
// may be deprecated in the future.

public final class DataSourceExample
{
  static public void main (String args[]) throws Exception
  {
    // Create an Firebird data source manually;
    
	org.firebirdsql.pool.FBWrappingDataSource dataSource = 
        new org.firebirdsql.pool.FBWrappingDataSource();

    // Set the standard properties
    dataSource.setDatabase ("c:/Programme/Firebird.152/examples/employee.fdb");
    dataSource.setDescription ("An example database of employees");

	/*
	 * Following properties were not deleted in order to show differences 
	 * between InterClient 2.01 data source implementation and Firebird one.
	 */
	
    //dataSource.setDataSourceName ("Employee");
    //dataSource.setPortNumber (3060);
    //dataSource.setNetworkProtocol ("jdbc:interbase:");
    //dataSource.setRoleName (null);
    
    // Set the non-standard properties
    //dataSource.setCharSet (interbase.interclient.CharacterEncodings.NONE);
    //dataSource.setSuggestedCachePages (0);
    //dataSource.setSweepOnConnect (false);
	
    // this some kind of equivalent to dataSource.setNetworkProtocol(String)
    // possible values are "type4", "type2" and "embedded".
	dataSource.setType("EMBEDDED");
    
    // SQL Role can be set like this:
    // 
    // dataSource.setRoleName("USER");
    
    // Character encoding for the connection is set to NONE
    dataSource.setEncoding("ISO8859_1");
    
    // other non-standard properties do not have setters
    // you can pass any DPB parameter
    //
    // dataSource.setNonStandardProperty("isc_dpb_sweep", null);
    // dataSource.setNonStandardProperty("isc_dpb_num_buffers", "75");
	
    // Connect to the Firebird DataSource
    try {
      dataSource.setLoginTimeout (10);
      java.sql.Connection c = dataSource.getConnection ("sysdba", "masterkey");
      
      java.sql.Statement stmt = c.createStatement();
      java.sql.ResultSet rs = stmt.executeQuery("SELECT * FROM employee");
      while(rs.next())
          System.out.println("a1 = " + rs.getString(1) + ", a2 = " + rs.getString(2));
          
      stmt.close();
      
      // At this point, there is no implicit driver instance
      // registered with the driver manager!
      System.out.println ("got connection");
      //c.close ();
    }
    catch (java.sql.SQLException e) {
		e.printStackTrace();
      System.out.println ("sql exception: " + e.getMessage ());
    }
  }
}
Tenta seguir o mesmo padrão.
G

lucas

vlw a forca ae, mas por algum motivo este problema está dando no meu windows vista, fez um teste agora no notebook do meu pai com windows XP, e não deu nem um problema já está incluindo normalmente a aplicação.

Vou acabar o trabalho no notebook, depois eu vejo como resolver isso

vlw ae pela ajuda de todos.

lucascaton

Blz cara, precisando, é só falar :wink:

TheKill

Reabrindo o topico.

Alguem teve problemas com collates e charSets
usando o firebird 2.5 embedded???

Esta complicado por aqui :slight_smile:

Criado 27 de setembro de 2008
Ultima resposta 2 de set. de 2010
Respostas 9
Participantes 4