How to Read Data From JavaDB

164 Views Asked by At

I have tried to create a simple Java application that will read data from the JavaDB. The purpose is to get the first "UNAME" variable from the database and assign it to the "user" variable and print it.

package giris;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 * @author Ibrahim
 */
public class Giris {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        String user = "";

        System.out.println("hello world");
        try 
        { 
            System.out.println("connecting to database");    
            Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/deneme", "ASD", "asd");
            System.out.println("succesfully connected");
            PreparedStatement pr = con.prepareStatement("select UNAME from ASD.Table1");

            ResultSet rs = pr.executeQuery();

            while(rs.next())
            {

            user = rs.getString(0);
            }
        }
        catch(Exception e)
        {
            System.err.println("error");
        }
        System.out.println(user);
    }

}

This is how my DB looks like

However, when I run the application the output is like this:

run:
hello world
connecting to database

error
BUILD SUCCESSFUL (total time: 0 seconds)
2

There are 2 best solutions below

0
Sarjit On BEST ANSWER

Loading driver class logic is missing, please add this

Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();

add this derbyclient-10.2.2.0.jar to classpath

hope it will help you

1
Adir Dayan On

You used it correctly, maybe wrong DB details.

BTW, never use catch block like that, you are missing the information stored in e.

Use below code for more information:

public static void yourMethod()
{
    try
    {
        // Some code...
    }
    catch(Exception e)
    {
        logError("Got exception during...", e);
    }
}

public static void logError(String message, Throwable e)
{
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);

    logError(message + "\n" + sw.toString());
}

public static void logError(String message)
{
    System.err.println("[ERROR] " + message);
}