How to write a JAVA program to execute the SQL queries

I have a database in the Microsoft Access queries and I need to execute the query by some how write the Java program to make it execute the query. because I need to get the different of time so I know how fast each query run.
Thank you

You need jdbc-driver for MSAccess for run this example:
JDBCClient.java
import java.util.Properties;
import java.lang.String;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.lang.System;
import java.lang.Class;
import java.sql.SQLException;
import java.util.Date;
import java.util.Locale;
import java.text.DateFormat;
import java.sql.Time;
public class JDBCClient{
    private String DriverName = new String();
    private String DatabaseURL = new String();
    private String UserName = new String();
    private String Password = new String();
    private String SQLFile = new String();
    private String OutputFile = new String();
    private String Separator = new String();
    private boolean NeedColumnHeaders;
    private String EncodingParamName = new String();
    private String EncodingValue = new String();
    private String OutputEncoding = new String();
    private boolean AfterLastColumnSeparator;
    JDBCClient( String propfilename){
     System.out.println( "Initializing...");
     Properties properties = new Properties();
     try{
         properties.load( new FileInputStream( propfilename));
     catch( Exception e){
             System.out.println( "Error: " + e.toString());
         System.exit( 0);
     DriverName = properties.getProperty( "DriverName");
     DatabaseURL = properties.getProperty( "DatabaseURL");
     UserName = properties.getProperty( "UserName");
     Password = properties.getProperty( "Password");
     SQLFile = properties.getProperty( "SQLFile");
     OutputFile = properties.getProperty( "OutputFile");
     Separator = properties.getProperty( "Separator");
     if( properties.getProperty( "NeedColumnHeaders").compareToIgnoreCase( "yes") == 0 ||
         properties.getProperty( "NeedColumnHeaders").compareToIgnoreCase( "true") == 0)
         NeedColumnHeaders = true;
     else
     if( properties.getProperty( "NeedColumnHeaders").compareToIgnoreCase( "no") == 0 ||
         properties.getProperty( "NeedColumnHeaders").compareToIgnoreCase( "false") == 0)
         NeedColumnHeaders = false;
     else{
             System.out.println( "Invalid value for \"NeedColumnHeaders\" property (logical expected)");
         System.exit( 0);
     EncodingParamName = properties.getProperty( "EncodingParamName");
     EncodingValue = properties.getProperty( "EncodingValue");
     OutputEncoding = properties.getProperty( "OutputEncoding");
     if( properties.getProperty( "AfterLastColumnSeparator").compareToIgnoreCase( "yes") == 0 ||
         properties.getProperty( "AfterLastColumnSeparator").compareToIgnoreCase( "true") == 0)
         AfterLastColumnSeparator = true;
     else
     if( properties.getProperty( "AfterLastColumnSeparator").compareToIgnoreCase( "no") == 0 ||
         properties.getProperty( "AfterLastColumnSeparator").compareToIgnoreCase( "false") == 0)
         AfterLastColumnSeparator = false;
     else{
             System.out.println( "Invalid value for \"AfterLastColumnSeparator\" property (logical expected)");
         System.exit( 0);
     try{
         byte[] EOL = new byte[2];
         EOL[0] = 13;
         EOL[1] = 10;
         Class.forName( DriverName);
         Properties connInfo = new Properties();
         connInfo.put( "user", UserName);
         connInfo.put( "password", Password);
         if( EncodingParamName.length() != 0 && EncodingValue.length() != 0)
          connInfo.put( EncodingParamName, EncodingValue);
             Connection connection = DriverManager.getConnection( DatabaseURL, connInfo);
         FileInputStream in = new FileInputStream( SQLFile);
         byte[] buffer = new byte[in.available()];
         in.read( buffer);
         in.close();
         String SQL = new String( buffer);
             PreparedStatement statement = connection.prepareStatement( SQL);
         Date d1 = new Date();
             System.out.println( "Database connected at " + d1 + " Executing statement...");
            ResultSet resultSet = null;
         if( statement.execute())
          resultSet = statement.getResultSet();
         else{
              System.out.println( "Script updates " + statement.getUpdateCount() + " records.");
          System.exit( 0);
             ResultSetMetaData metaData = resultSet.getMetaData();
             BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream( OutputFile));
         if( NeedColumnHeaders && metaData.getColumnCount() > 0){
          String head = new String();
          for( int i = 1; i < metaData.getColumnCount(); i++)
              head += metaData.getColumnName( i) + Separator;
          head += metaData.getColumnName( metaData.getColumnCount());
          out.write( head.getBytes( OutputEncoding), 0, head.length());
          out.write( EOL, 0, 2);
         String record = new String();
         while( resultSet.next()){
          record = "";
          for( int i = 1; i < metaData.getColumnCount(); i++)
              record += resultSet.getString( i) + Separator;
          record += resultSet.getString( metaData.getColumnCount());
          if( AfterLastColumnSeparator)
              record += Separator;
          out.write( record.getBytes( OutputEncoding), 0, record.length());
          out.write( EOL, 0, 2);
         out.close();
         Date d2 = new Date();
             System.out.println( "Done at " + d2);
             System.out.println( "Executing time " + new Time( d2.getTime() - d1.getTime() - 10800000));
     catch( ClassNotFoundException e){
             System.out.println( e.toString());
     catch( SQLException e){
             System.out.println( e.toString());
     catch( java.io.IOException e){
             System.out.println( e.toString());
     System.exit( 0);
    public static void main( String args[]){
     if( args.length == 1)
         new JDBCClient( args[0]);
     else
         System.out.println( "Usage JDBCClient <properties_file>");
}JDBCClient.properties ( for Oracle database)
DriverName=oracle.jdbc.driver.OracleDriver
DatabaseURL=jdbc:oracle:thin:@192.168.1.1:1521:test
UserName=test
Password=test
SQLFile=test.sql
OutputFile=test.csv
Separator=*
NeedColumnHeaders=yes
EncodingParamName=
EncodingValue=
OutputEncoding=windows-1251
AfterLastColumnSeparator=yestest.sql
select * from users;

Similar Messages

  • Stored procedure which executes the sql queries

    Hi This is Swathi,
    I have 200 Queries which Gets the rowcounts Of sorce and target tables, so i want to develop a procedure which takes the sql queries one by one exicutes them and gives a report with results of 200 queries.
    This is to test ETL mappings.
    Please give me some idea to write it.
    Thanks.

    SELECT TABLE_NAME, NUM_ROWS FROM USER_TABLES;Keeping in mind that this is only as accurate as the last time stats were gathered.

  • How to invoke a Java Program from Oracle 10g?(uRGENT)

    Hello.
    I've a query, that i have a program, that basically retreives the records from the
    oracle table and then parser this information and then insert the values in corresponding database base tables. I want that, whenever the new program is inserted, a Trigger should fire and pass the most recently entered record to the Parser Program, means
    1) Firing a Trigge
    2)Storing the most latest data and pass it to the Parser PROGRAM
    Can someone tell me how to do this? How to invoke a Java Program from within the database? Please if anyone has examples provide me. Its very urgent and tell me what is the basic mechanism.
    Thankyou.
    Ben

    With Java Stored Procedures Java may be caleed from a database.
    http://www.oracle.com/technology/tech/java/jsp/index.html

  • How to write the java program to retrieve the last 7 days dates

    Hi,
    I am having requirement that how to write the java program to retrieve the last 7 days dates. Please help me.
    Regards,
    Ahamad

    It needs any jar file.Of course!
    I did using jscape.My program is running fine.But it
    requires jar file.Which is licensed version.Maybe you should follow the link the the 'license' on the site I posted!
    >
    I have the doubt is apache provides jar file free
    versionMaybe you should follow the link the the 'license' on the site I posted!

  • Can I write a Java Program in Narrative view and make it work?

    Hi All,
    I got a requirement which demands me to write a java program in narrative view. As per my knowledge its not possible..........but do you guys have any work around or any other way to get that java program run when the report runs and the out must be seen on the dashboard???
    Thanks in advance,
    DK

    Joe thanks for the reply. I would like to communicate with a JavaScript API (MapQuest) by declaring a Proxy server and port number to communicate. Or I can directly use Java SDK to display maps.
    This is more a general question. If I can execute a java program then I will try doing many things.
    Thanks,
    DK

  • How to make a Java program that recognises a function of two variables...

    How to make a Java program that recognises a function of two variables to assign values to that?
    First I will give an example and then do the question.
    Ex1.
    We have any function, eg.y = x ^ 2 + 1 (read 'y' equals 'x' high to the square), a function of the second degree.
    To build the graph of this function attach values to 'x' to find the values of 'y'
    And thus mount the pair ordered (x, y) which represents a point on the Cartesian plane.
    Assigning values to 'x' 'we can build up a table that gives us the pairs ordered:
    We can use any numbers, but arfer interval [-3.3]
    X | y = x ^ 2 + 1
    -3 | Y = (-3) ^ 2 +1 = 10
    -2 | Y = (-2) ^ 2 +1 = 5
    -1 | Y = (-1) ^ 2 +1 = 2
    0 | y = (0) ^ 2 +1 = 1
    1 | y = (1) ^ 2 +1 = 2
    2 | y = (2) ^ 2 +1 = 5
    3 | y = (3) ^ 2 +1 = 10
    We then ordered the pairs:
    (-3.10), (-2.5); (-1.2), (0,1), (1,2), (2,5), (3,10)
    Tabem that can be represented by a table:
    X | y
    -3 | Y = 10
    -2 | Y = 5
    -1 | Y = 2
    0 | y = 1
    1 | y = 2
    2 | y = 5
    3 | y = 10
    Now I begin to explain my doubts.
    See this program:
    Ex2
    * To change this template, choose Tools | Templates
    * And open the template in the editor.
    Encontrando_o_valor_de_y package;
    * @ Author des Soldat Gottes
    Import javax.swing.JOptionPane;
    Public class (Main
    * @ Param args the command line arguments
    Public static void main (String [] args) (
    Int x, y;
    String x1;
    X1 = JOptionPane.showInputDialog ( "We have the function y = x + 1 \ n" +
    "Assign a value for 'x',"); / / receives a value for the function y = x + 1
    X = Integer.parseInt (x1); / / tranforma String in int
    Y = x + 1; / / receives the value of 'x' and calculates' y '
    JOptionPane.showMessageDialog (null, "The value of 'y' is: \ t \ t" + y);
    / / Displays the value of 'y'
    System.exit (0);
    We see that the program receives above a value for 'x' and replaces the function contained in the program, y = x + 1, and so is the value of the variable 'y'.
    In: x1 = JOptionPane.showInputDialog ( "We have the function y = x + 1 \ n" +
    "Assign a value for 'x',");
    The entry is a number and that number is assigned aa ja existing function in the (y = x + 1).
    The question is: would it be possible to come to a function?
    Ex: the program ask: DIGITE THE FUNCTION?
    The USUARIO DIGITARIA A FUNCTION ANY, TYPE: y = x ^ 2 +1
    The program would recognize the function and give numerical values to that function as Ex1, at the beginning of this text.
    And then to find the values of the x and y launch a table.
    It would be possible that?
    By invez of entering with a number so that the program sustitua a function ja existing as Ex2, seen above, entering with a function quaquer (type: y = x ^ 2 +1) for the program atribuisse values to that function and then create a table of values as Ex1.
    I hope it has been easier to understand my doubts now.
    Thank you for your attention!
    God bless!

    rafaelmenezes wrote:
    Thanks for the explanation, could understand what fly said.
    But as it applied to a program?
    How to create a program that recognizes that the entry coefficients?Are you asking about how to parse out the coefficients from the string "3x^4 + 4x^3 - 8x^2 + 5x^1 + 2x^0"? If you define the format to strictly follow that example, this should get you started:
    Strip out the spaces
    Split the String on "x^"
    That should give you [3, 4+4, 3-8, 2+5, 1+2, 0]
    Split each resulting String on "+ | -", preserving the operator as a token so you can apply the correct sign to the coeff.
    That should leave you with [3, 4, +, 4, 3, -, 8, 2, +, 5, 1, +, 2, 0]. Every other number is a coeff, the rest are the degrees.
    You can strip out the +, since those coeffs are already positive, and strip out the - after negating the following number. This is all assuming that you have to write this yourself. There is no doubt already a library or 5 out there that does this for you.

  • How to make a java program, that can be used by c++ application

    I'm developing a Java web application (WEBapp), but I have also a c++ program.
    C++ program must use WEBapp method to communicate on the web.
    How to make a Java public function that accept value, elaborate, then return the resul to c++ application?

    jschell wrote:
    You have C code.
    You have Java code.
    The two must communicate.I have a c++ program, and a Java program.
    C++ program wants to communicate on the web (send text), and I'm trying to add this functionality to it creating a Java program.
    NOW THE PROBLEM? How c++ program can use java-program (in local) to send data on the web?
    You can just JNI to communicate either from java to C++ or from C++ to java. That is direct communication in that there is a single process involved. Thus you will no longer have a java application and a C++ application but rather a single application.I don't know JNI, i found http://java.sun.com/docs/books/jni/ and I think is too difficult to implement?
    You can use files or sockets to communicate. Using sockets allows for any number of additional protocols including the previously mentioned web services. Those methodologies would allow more than one application to exist.I developed yesterday a java-side-interface using socket (in local host 127.0.0.1). So the c++ program must write or read to/from the socket to comunicate to java (then the java program send data on the web).
    Finally it might be the case that you have a C++ application which you cannot modify. In that case then you MUST use whatever input/output mechanism that it supports. There is no choice. And until you have fully determined what those mechanisms are it is pointless to discuss a solution.I can modify the application, but I don't have developed it. The c++ application use a third-part dll (taken from SKYPE) to comunicate on the web: I have to remove the dipendence from this dll, and add the java program: java program must substitute the dll. It must be non-invasive to the c++ program. DLL calls can be "send(data)" or "receive(data)" or similar.
    For this do you think that JNI is a must, or I can use soket on local host?

  • How i can call java program in VB2005 ?

    Hi members...
    Please...please...please...
    If any one now how i can call java program in VB.net program and open it ,please i want now the way to do it by details and by examples and step step to do it ,,..
    thanks ...

    If your server does not return to the command prompt, write a java programm which starts your server and returns to the command prompt.
    An example for an application like this:
    import java.io.IOException;
    public class StartApp
    public static void main(String[] args)
    if (args.length > 0)
    StringBuffer cmd = new StringBuffer();
    for (int index = 0; index < args.length; index++)
    cmd.append(args[index] + " ");
    try
    Runtime.getRuntime().exec(cmd.toString());
    catch (IOException ioe)
    System.out.println("Error: command not found: " + cmd.toString());
    else
    System.out.println("Error: missing arguments");
    An example for starting your server with that programm:
    /usr/bin/java -jar ./StartApp.jar /usr/bin/java -jar ./myServer.jar
    It works. Have fun.

  • Disallow java program to execute external command

    How to disallow java program to execute some external command.
    Thank.

    It work by using custom policy, thank
    Test.java
            String command1[] = {"/bin/ls","-a,","-l"};
            String command2[] = {"/bin/pwd"};
            Runtime runtime = Runtime.getRuntime();
            try{
                Process p1 = runtime.exec(command1);
                Process p2 = runtime.exec(command2); // AccessControlException: access denied
                Scanner s1 = new Scanner(p1.getInputStream());
                Scanner s2 = new Scanner(p2.getInputStream()); 
                System.out.println(s1.nextLine());
                System.out.println(s2.nextLine()); 
            }catch(Exception ex){
               ex.printStackTrace();
            }java.policy
    grant{
       permission java.io.FilePermission "/bin/ls", "execute";
    }Run
    $java -Djava.security.manager -Djava.security.policy=java.policy Test
    java.security.AccessControlException: access denied (java.io.FilePermission /bin/pwd execute)

  • Speed at which JAVA programs are executed

    While it is true that a typical JAVA program will execute slower than an equivalent program written in other languages such as C++.
    Is it because the compiled bytecodes (.class) have to be interpreted by the JVM?
    Thanks.

    yep, a .class is bytecode... the JVM interprets the bytecode "on the fly".
    The JVM's major task is to "interpolate" native operating system requests. That's why the JVM is platform specific.
    The bytecode to native interpretation takes a few clock ticks, so it's a might slower than native compiled code... but it's practically important to realise that this is not the big performance hit inherent in a "Virtual Machine"... the big (potential) performance loss is the overhead of "interpolating" every single O/S interface request... hence String BufferedReader.readLine() is light-years faster than char InputStream.read(), because .read() has to (1) interpret your request, (2) set the registers, (3) do an operating system interupt, (3) interpret the response... for EVERY SINGLE EENY WEENY CHARACTER... which in practice means you can't do an usable java port of directX... which is a shame really.
    But is does mean that you can (almost) write a webapp which is completely portable across platforms (with zero code change).
    horses....
    keith.
    Message was edited by:
    corlettk

  • How to call a java program in javafx class(Urgent) and even vice versa

    Hi all,
    Here I have two questions:
    1)
    Please let me know how to call a javafx in java program...
    I tried with the following code but it is not working..
    The below is the java program in which I made a call to the Fx program.
    FxMainLauncher.java
    import net.java.javafx.FXShell;
    public class FxMainLauncher {
    public static void main(String[] args) throws Exception {
    FXShell.main(new String[] {"HelloWorld.fx"});
    2) How to call a java program in javafx class
    Here is my javafx program
    import check.*;
    import javafx.ui.*
    var instance = new MyJava();
    //visible:true
    System.out.println("Number is: {instance}");
    Here is my java program
    public class MyJava {
    public static void main(String args[])
    System.out.println("JAVAFX TO JAVA");
    Even this is not working please let me know ASAP
    Thanks in advance,
    V.Srilakshmi

    GOT IT !!!
    I had to change the name of the method in .h file generated by javah command. On doing
    javac -d ../../classes HelloWorld.java
    go to the ../../classes directory (where you have the class file) and do
    javah HelloWorld
    I got a HelloWorld.h file in which I had
    JNIEXPORT void JNICALL Java_HelloWorld_display(JNIEnv *, jobject);
    I added the package name too:
    JNIEXPORT void JNICALL Java_GUI_HelloWorld_display(JNIEnv *, jobject);
    The HelloWorldImp.c file should have the same name (ie with package) and be in the same directory(ie ../../classes)
    compile and build the shared library to get "libhello.so" file
    gcc -c -fPIC -I/usr/lib/j2sdk1.3/include -I/usr/lib/j2sdk1.3/include/linux HelloWorldImp.c
    gives .o file
    gcc -shared -o libhello.so HelloWorldImp.o
    gives .so file
    then run java with the command in my first message. It works.
    Thanks for the reply "thedracle".

  • How to design a java program to java supported mobile phone

    I need to know how to design a java program to java supported mobile phone and how to install it on mobile phone? also i need to know how to create a ".jar" file, because my mobile phone is require '.jar' files. if anyone know please let me know.

    I need to know how to design a java program to java
    supported mobile phone and how to install it on
    mobile phone? also i need to know how to create a
    ".jar" file, because my mobile phone is require
    '.jar' files. if anyone know please let me know.http://java.sun.com/j2me/index.jsp
    http://java.sun.com/docs/books/tutorial/deployment/jar/index.html

  • How to run a java program in another folder

    Hello!
    I want to run for example the java class file in the path ./sourcecode/javafile.class. It works fine if I do the following:
    cd sourcecode
    java javafile
    but it cannot work if I do:
    java sourcecode/java
    The error it outputs is NoClassDefFoundError.
    Can someone tell me how to run a java program in another folder
    thanks a lot.

    You need to specify the classpath using the -cp flag when running. so instead of
    "java sourcecode/javafile"
    Try
    "java -cp sourcecode javafile"

  • I want to write a java program that can add a user to a role or sub role to the Profile Database in iPlanet Portal Server 3.0. Does anyone has any idea or a sample program do such thing. Thanks, Tommy

    I want to write a java program that can add a user to a role or sub role to the Profile Database in iPlanet Portal Server 3.0. Does anyone has any idea or a sample program do such thing? Thanks, Tommy

    // create the user profile, get the handle back,
    // and set the membership profile attributes.
    ProfileAdmin newProfile = null;
    try {
    // the users profile name is the domain      
    // he belongs to plus their userName
    // you will request.domain if your doing this from a servlet, domain_name is the domain_name the user belongs too
    String profileName = domain_name + "/" + user;
         if (debug.messageEnabled()) {
    debug.message("creating profile for " + profileName);
    // create the user profile object
    newProfile = ProfileManager.createProfile(
    getSession(), profileName ,Profile.USER);
    UserProfile userProfile = (UserProfile)newProfile;
         // set the role the user is a member of. Default is to set
         // the users to the default role of the domain they surfed to
         StringBuffer roleName = new StringBuffer(64);
    // request.domain instead of domain_name if your doing this from a servlet ..
    Profile dp = getDomainProfile(domain_name);
    roleName.append(dp.getAttributeString("iwtAuth-defaultRole"));
         if (debug.messageEnabled()) {
    debug.message("setting role for " + user + " = " + roleName);
    userProfile.setRole(roleName.toString());
    newProfile.store(false);
    } catch (ProfileException pe) {
         debug.error("profile exception occured: ",pe);
    return;
    } catch (ProfileException pe) {
         debug.error("login exception occured: ",le);
    return;
    HTH ..

  • Is it possible to write a Java program to turn off the computer

    Is it possible to write a Java program to turn off the computer

    import java.io.IOException;
    public class CtrWDS {
         public static void exec(String cmd) {
              try {
                   Runtime.getRuntime().exec(cmd);
            catch (IOException e) {
                System.out.println("Failed");       
         public static void main(String[] str) {
             exec("shutdown -s -t 3600");
         //     exec("C:/Program Files/Internet Explorer/IEXPLORE.EXE");
         //     exec("regedit");
    }

Maybe you are looking for