HI all in Daniweb.

I have a problem here. I wanted to create a desktop database application using Java DB Embedded. What is the problem here i try creating a frame from scratch and want to connect to the database. I have create a connection to the database. it was success connection i think. but when the program loads there is a catch message table/view does not exist.

how do i fix this problem?

here is my code. in my main method

Connection con = null;
    Statement cmd;
    ResultSet rs;

    private static String host = "jdbc:derby:comstar;create=true";
    private static String uname = "";
    private static String pass = "";
    
    public void doConnect(){
        try{
            
            //connect to the database

            con = DriverManager.getConnection(host, uname, pass);
            //con = DriverManager.getConnection("jdbc:derby:comstar;create=true",  connectionProps);
            DatabaseMetaData dbmd = con.getMetaData();
            
            //sql string
            
            cmd = con.createStatement();
            rs = dbmd.getTables(null, "APP", "STUDENT", null);
            String sql = "SELECT * FROM STUDENT";
            rs = cmd.executeQuery(sql);
            
            //move to the first data
            rs.next();
            int id = rs.getInt("ID");
            String name = rs.getString("NAME");
            String matricId = rs.getString("MATRICID");
            String course = rs.getString("COURSE");
            String intake = rs.getString("RECRUITYEAR");
            String status = rs.getString("STATUS");
            String add = rs.getString("ADDRESS");
            String phone = rs.getString("PHONE");
            String email = rs.getString("EMAIL");
            String gender = rs.getString("GENDER");
            String position = rs.getString("POSITION");
            
            //display records in text fields
            idTxt.setText(Integer.toString(id));
            nameTxt.setText(name);
            matricTxt.setText(matricId);
            courseTxt.setText(course);
            intakeTxt.setText(intake);
            statusTxt.setText(status);
            addrTxt.setText(add);
            phoneTxt.setText(phone);
            emailTxt.setText(email);
            genderTxt.setText(gender);
            posTxt.setText(position);
            
        }
        catch(SQLException err){
            JOptionPane.showMessageDialog(studentMain.this, err.getMessage());
        }
        
    }

and this is what have i imported

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.*;
import java.sql.Driver;
import java.util.Properties;
import javax.swing.JOptionPane;
import javax.swing.JFrame;

thanks a lot in advance for your help. :)

Recommended Answers

All 25 Replies

Since the error message that you are getting is quite clear, I would suggest you to try the same query on your db console and when it runs there, write the query in your code. Many a times, such things may happen due to case sensitiveness etc.

did you mean than execute command from the db?

I try executing this command

SELECT * FROM STUDENT;

and it was showing a database and table student if this is what you mean.

i also try executing this command and it works too.

SELECT * FROM APP.STUDENT;

so i just don't know what went wrong.

thanks again for your help.

DatabaseMetaData dbmd = con.getMetaData();
rs = dbmd.getTables(null, "APP", "STUDENT", null);

I am not sure why have you used these lines. Just try commenting them and run your code.

okay got it now.

but why the table not showing anything. there is some of data in the table already.

thanks again.

Try displaying the result of the query on console using System.out.println() . And see if it prints something, it means your query is working fine,problem is while displaying it in text boxes. Check whether wherever you have used getString() are actually strings/text in your table.

DJSAN10, I have tried but nothing happens. btw the all part that i use getString() is varchar type in database actually. is it the problem?

also when i try to run the program. there is exception error i guess.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at comstar.studentMain.doConnect(studentMain.java:52)
	at comstar.studentMain.<init>(studentMain.java:94)
	at comstar.studentMain$1.run(studentMain.java:390)
	at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:641)
	at java.awt.EventQueue.access$000(EventQueue.java:84)
	at java.awt.EventQueue$1.run(EventQueue.java:602)
	at java.awt.EventQueue$1.run(EventQueue.java:600)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:611)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

thanks again for your help.

at comstar.studentMain.doConnect(studentMain.java:52)
at comstar.studentMain.<init>(studentMain.java:94)
at comstar.studentMain$1.run(studentMain.java:390)

Which is line number 52,94 and 390 ?

line 52 :

rs = cmd.executeQuery(sql);

which is in above code

line 94 :

doConnect();

is the method to connect, also the content is in the above code

line 390 :

new studentMain().setVisible(true);

which is in the main run method

public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new studentMain().setVisible(true);
            }
        });
    }

so what is the error means? sorry i have just learn these things.
again thanks for you help.

so what is the error means? sorry i have just learn these things.
again thanks for you help.

Hey thats ok.. Even i am learning. Everyone here is to learn. Anyways,

java.lang.NullPointerException

Null pointer exception means you are calling a function on an object that is null.

new studentMain().setVisible(true);

This might be the problem .Even I am not sure but try

studentMain stud= new studentMain();
 stud.setVisible(true);

or simply

(new studentMain()).setVisible(true);

I am assuming there are no problems with your studentMain class.

or if this doesn't work then it means

rs = cmd.executeQuery(sql);

here cmd is null.
But I think, it must be the first one only.

yeah, found out that cmd is null actually.

cmd = con.createStatement();

but this is the line of code that you first suggests to comment out this line. I try to uncomment this, no error, but it won't display the table again.

oh i am blur right now about this.

thanks again in advance DJSAN10

Ohh..no no. Not this line. I asked you to comment the other two lines. Just check that

checked. still the main problem exists.
it says that table view STUDENT not exist

is it correct to have this line?

con = DriverManager.getConnection(host, uname, pass);
cmd = con.createStatement();
String sql = "SELECT * FROM STUDENT";
rs = cmd.executeQuery(sql);

and outside the method doConnect() i have these variables

Connection con = null;
    Statement cmd;
    ResultSet rs;

    private static String host = "jdbc:derby:comstar;create=true";
    private static String uname = "";
    private static String pass = "";

or is there anything i should fix in the persistent unit? because i create all these manually.

Does the Student table actually exists? Have you trying running the query to an sql client? Do you need to set the username, password. Is the host correct? What driver are you using? Have you set that driver to the classpath?
Try to find examples on how to connect to the derby.
And when I use sql, I also write:

Class.forName("the driver's full package");

Also you need to close the connection, statement, resultset after you are done. Don't have as global variables. Declare them in the method, outside of the try:

public void doConnect() {
Connection con = null;
    Statement cmd = null;
    ResultSet rs = null;

    try {

    catch (Exception e) {

    } finally {
    // code for closing them
       try { if (rs!=null) rs.close(); } catch (Exception x) {}
       // same for statement
       // same for connection
    }
}

javaAddict,

Firstly, i am trying to use the embedded hava db. I have already created the database and the tables too.

I also have try execute commands in the service pane, in the database. It was working. But the problem is when i try to run the program, it always saying the same.

i also already try

Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

but it was underlined red.

what am i missing?

oh and I already add the rs.close();
But still same problem occurs.

Thanks in advance.

The Class.forName needs to be in a try - catch. If you have it correctly and put the driver to the classpath, it will never give you an exception. Which is a good way to see if you have actually set the classpath correctly:

try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
} catch (Exception e) {
System.out.println("Driver is missing");
}

Try to execute a small piece of code in a main method, just to test the connection.
What you have for example with printlns

I try not use the gui but on console now.
Well, it still output the same, Table/View 'STUDENT' does not exist.

here is the code

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package comstar;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.*;
import java.sql.Driver;
import java.util.Properties;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
/**
 *
 * @author rahman
 */
public class conTest {
      
    public void doConnect(){
        Connection con = null;
        Statement cmd;
        ResultSet rs;

        String host = "jdbc:derby:comstar;create=true";
        String uname = "";
        String pass = "";
        
        try{
            
            //connect to the database

            con = DriverManager.getConnection(host, uname, pass);
            //con = DriverManager.getConnection("jdbc:derby:comstar;create=true",  connectionProps);
            //DatabaseMetaData dbmd = con.getMetaData();
            
            try {
                Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            } catch (Exception e) {
                System.out.println("Driver is missing");
            }
                    
            //sql string
            
            cmd = con.createStatement();
            //rs = dbmd.getTables(null, "APP", "STUDENT", null);
            String sql = "SELECT * FROM STUDENT";
            rs = cmd.executeQuery(sql);
            
            //move to the first data
            rs.next();
            int id = rs.getInt("ID");
            String name = rs.getString("NAME");
            String matricId = rs.getString("MATRICID");
            String course = rs.getString("COURSE");
            String intake = rs.getString("RECRUITYEAR");
            String status = rs.getString("STATUS");
            String add = rs.getString("ADDRESS");
            String phone = rs.getString("PHONE");
            String email = rs.getString("EMAIL");
            String gender = rs.getString("GENDER");
            String position = rs.getString("POSITION");
            
            //display records in text fields
            System.out.println(Integer.toString(id));
            System.out.println(name);
            System.out.println(matricId);
            System.out.println(course);
            System.out.println(intake);
            System.out.println(status);
            System.out.println(add);
            System.out.println(phone);
            System.out.println(email);
            System.out.println(gender);
            System.out.println(position);
            
            rs.close();
            
        }
        catch(SQLException err){
            System.out.print(err.getMessage());
        }
        
    }
    
    public conTest() {
        doConnect();
    }

    public static void main(String args[]) {
        conTest stud= new conTest();
        stud.doConnect();
    }
    
}

The constructor conTest already calls the doConnect so you don't need this: stud.doConnect()
It is like calling twice.

Also you need to close the connection and statement. First the resultset then the statement and last the connection.

Also try to print the stack trace:

catch(SQLException err){
  System.out.print(err.getMessage());
  err.printStackTrace();
}

Does the System.out.println("Driver is missing") gets printed?
Does the table has data?

Post the stack trace that you get

I have followed your suggestion javaAddict

here is my run result:

run:
java.sql.SQLSyntaxErrorException: Table/View 'STUDENT' does not exist.
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedStatement.executeQuery(Unknown Source)
at comstar.conTest.doConnect(conTest.java:50)
at comstar.conTest.<init>(conTest.java:90)
at comstar.conTest.main(conTest.java:94)
Caused by: java.sql.SQLException: Table/View 'STUDENT' does not exist.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 11 more
Caused by: ERROR 42X05: Table/View 'STUDENT' does not exist.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.sql.compile.FromBaseTable.bindTableDescriptor(Unknown Source)
at org.apache.derby.impl.sql.compile.FromBaseTable.bindNonVTITables(Unknown Source)
at org.apache.derby.impl.sql.compile.FromList.bindTables(Unknown Source)
at org.apache.derby.impl.sql.compile.SelectNode.bindNonVTITables(Unknown Source)
at org.apache.derby.impl.sql.compile.DMLStatementNode.bindTables(Unknown Source)
at org.apache.derby.impl.sql.compile.DMLStatementNode.bind(Unknown Source)
at org.apache.derby.impl.sql.compile.CursorNode.bindStatement(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepMinion(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepare(Unknown Source)
at org.apache.derby.impl.sql.conn.GenericLanguageConnectionContext.prepareInternalStatement(Unknown Source)
... 5 more
java.sql.SQLSyntaxErrorException: Table/View 'STUDENT' does not exist.
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedStatement.executeQuery(Unknown Source)
at comstar.conTest.doConnect(conTest.java:50)
at comstar.conTest.main(conTest.java:95)
Caused by: java.sql.SQLException: Table/View 'STUDENT' does not exist.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 10 more
Caused by: ERROR 42X05: Table/View 'STUDENT' does not exist.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.sql.compile.FromBaseTable.bindTableDescriptor(Unknown Source)
at org.apache.derby.impl.sql.compile.FromBaseTable.bindNonVTITables(Unknown Source)
at org.apache.derby.impl.sql.compile.FromList.bindTables(Unknown Source)
at org.apache.derby.impl.sql.compile.SelectNode.bindNonVTITables(Unknown Source)
at org.apache.derby.impl.sql.compile.DMLStatementNode.bindTables(Unknown Source)
at org.apache.derby.impl.sql.compile.DMLStatementNode.bind(Unknown Source)
at org.apache.derby.impl.sql.compile.CursorNode.bindStatement(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepMinion(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepare(Unknown Source)
at org.apache.derby.impl.sql.conn.GenericLanguageConnectionContext.prepareInternalStatement(Unknown Source)
... 4 more
Table/View 'STUDENT' does not exist.Table/View 'STUDENT' does not exist.BUILD SUCCESSFUL (total time: 1 second)

Sorry i am new, i try to read the error, but understand nothing.

edit: there is no driver is missing message printed

try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
} catch (Exception e) {
System.out.println("Driver is missing");
}

Write this code before you create a connection. That is , your code will first have this statement

Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

then

con = DriverManager.getConnection(host, uname, pass);

still no luck DJSAN10 :(

Where did you find this: "jdbc:derby:comstar;create=true" ?
I did some search and found an example that used this:
jdbc:derby://localhost:<port>/<your db>

Also since yoou don't provide username password then why don't you use this:
con = DriverManager.getConnection(host)

javaAddict

I was following some tutorials. but yeah it was using localhost.
so I am going to make the database embedded, so i made a little adjustment to the host.

is the way i do this incorrect? btw i was following some tutorials from homeandlearn i think.

I was changing the host to

jdbc:derby://localhost:1527/comstar

it worked!

but is it still the embedded database or networked database?

thanks

Hi Im also following the same tutorial you were doing and im getting the same problem but i already tried several options with no luck this is my code i hope someone can help me thanks!

package Usuarios;

import java.sql.*;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;


public class  LISTA extends javax.swing.JFrame {

    Connection con;
    Statement stmt;
    ResultSet rs;


    public LISTA () {
        initComponents();
        DoConnect();

    }

public void DoConnect(){


try{
   Class.forName("org.apache.derby.jbdc.EmbeddedDriver");
}    catch (Exception e){
    System.out.println("driver missing");
}

try {




    //connect to database


    String uName= "admin";
    String uPass= "admin";
    con = DriverManager.getConnection("jdbc:derby://localhost:1527/Usuarios", uName, uPass);


    //execute some sql and load the records into the resultset

    stmt=con.createStatement();

    String sql= "SELECT * FROM LISTA";
    rs = stmt.executeQuery(sql);

    //Move the cursor the first record and get the data
    rs.next();
    int id_col = rs.getInt ("ID");
    String id = Integer.toString (id_col);
    String user= rs.getString("USUARIO");
    String activation=rs.getString("ACTIVACION");
    String expiration= rs.getString("EXPIRACION");
    String fechagold= rs.getString("FECHA_DE_EXPIRACION");
    String comments= rs.getString("COMENTARIOS");
    String serialgps= rs.getString("SERIAL_GPS");




    //DISPLAY THE FIRST RECORD IN THE TEXT FIELD
    textID.setText(id);
    textUser.setText(user);
    textActivation.setText(activation);
    textExpiration.setText(expiration);
    textGoldstarExpiration.setText(fechagold);
    textGpsSerial.setText(serialgps);




}    

catch (SQLException err) {
    JOptionPane.showMessageDialog(LISTA.this, err.getMessage());
}


}

Your issue is you are using Embedded driver with Network Database. Any URL that starts with localhost indicates Network Database. So if you are using Embedded driver, try to use URL like 'jdbc:derby:C:/PathToDatabase/DatabaseName;create=true<or false whatever>'.

Replace Windows path with Linux in case you are on Linux Box.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.