Database query from Java

I'm writing a Java program that needs to query a Microsoft Access database. I'm not sure how to do this. Someone said to use ODBC drivers but I don't know what these are. Any clarification/ideas would be appreciated.

There are a few easy step to set up a connection to your database in your java program.
1. establish an odbc data source in windows control panel (may be under Administrative tools).
2. you need to import the java.sql package.
3. you need a connection, so type the following into your database class:
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection("jdbc:odbc:/*your data source name goes here*/");
catch (ClassNotFoundException exception)
System.err.println("Failed to load JDBC/ODBC driver");
exception.printStackTrace();
System.exit(1);
catch (SQLException exception)
System.err.println("Unable to connect");
exception.printStackTrace();
System.exit(1);
}4. Find an SQL tutorial on the web.
5. For each query/update etc create a Statement object using the following code:
try
Statement statement = connection.createStatement();
/* now use the remainder of this try block to execute your query. Each database query returns a ResultSet object */
ResultSet resultSet = statement.executeQuery("/*your query string goes here*/");
/* the next() method in ResultSet returns true if there are any more records, like an iterator. Therefore, you know if there are any results or not*/
if (resultSet.next())
/* If your query was a 'SELECT * FROM ...etc' then you will get a whole row from the table(s) within the database. if you need to extract a number from that record and you know the column number, then use the following */
int id = resultSet.getInt(1);
/* where 1 corresponds to the first column in the table, and so on. Ifyou want to extract a String, the use the getString() method*/
catch (SQLException exception)
}That's basically the easiest way to go about it (I think). Best to consult a book for a more in-depth look. Try Java - How to Program, by Deitel and Deitel (available at www.deitel.com). I found this very useful.

Similar Messages

  • BEx Query from Java

    Hi
    Can I call a BEx Query from Java . If yes, in what format data will be returned? We just need data, we want to structure it in Java for display in a Flex UI.
    Please note that I have very limited knowledge of both Java and BI.
    Thanks in advance for your help.
    Best Regards
    Saurabh

    Hi,
    Yes you can. It will be contained in a web template.
    Please read through the link below and the related links contained within.
    http://help.sap.com/saphelp_nw70ehp1/helpdata/en/0d/af12403dbedd5fe10000000a155106/frameset.htm
    Thanks,
    Michael
    Edited by: Michael Devine on May 25, 2010 3:40 PM

  • Any ideas how to execute a .sql file on database server from java?

    Any ideas how to execute a xyz.sql file (which is fisically on
    database server) from java?
    thanks

    Try
    sqlplus "sys/oracletest as sysdba" @bpk.sql
    Working locally, and having set the ORACLE_SID, you don't need to specify the SqlNet alias (@testdb).
    Remember to put an exit at the end of the bpk.sql script.

  • Best practice for database calls from Java components?

    I have a java component that encapsulates some complex database logic. In unit tests, I pass in a jdbc connection.
    Is there a way to pass in a database connection from PBL for a database defined as an External Resource in an ALBPM project? That way, I can test it using the "abstract" definition in the project and know that when it is deployed to production it will use the concrete definition. And, I won't have to maintain a separate configuration of the JDBC url.
    Is there a better way to do this? Or is it possible?
    Thanks,
    Todd

    Hi Bruno,
    The main issue with the combination of stateful session beans and servlets is the servlet threading model.
    It is dangerous to store a stateful session bean reference in servlet instance state, since the servlet instance
    can be accessed concurrently, yet a stateful session bean reference is intended to be used by only one
    client.
    As you point out, one alternative is to store the reference in the HttpSession. That associates the reference
    with a particular client, which matches the stateful session bean programming model.

  • Problem when connecting locally to Oracle Database 10g from Java code

    Good afternoon,
    I try to connect to my local Oracle 10g from JAVA code. Could somebody tells me what are the 'values' to enter in place of 'value1, value2, value3' in the following:
    final String connectionURLThin = "jdbc:oracle:thin:@value1:value2:value3";
    I tried to put my 'user' and 'pw' credentials I used when connecting with SQL*PLUS:
    value1=my_user_name
    value2=my_pw
    value3=my_schema
    but it doest work. Besides where could have I to put the 'WORKSPACE" name?
    Thanks for any help.
    Claude
    Details:
    ERR MESSAGE----------------------
    Exception in thread "main" java.lang.NoClassDefFoundError: oracle/dms/instrument/ExecutionContextForJDBC
    at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:365)
    at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
    at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:854)
    at java.sql.DriverManager.getConnection(DriverManager.java:620)
    at java.sql.DriverManager.getConnection(DriverManager.java:200)
    at javaapplication6.ConnectionExample.driverManager(ConnectionExample.java:138)
    at javaapplication6.Main.main(Main.java:36)
    Caused by: java.lang.ClassNotFoundException: oracle.dms.instrument.ExecutionContextForJDBC
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:319)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:264)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:332)
    ... 8 more
    Java Result: 1
    BUILD SUCCESSFUL (total time: 0 seconds)
    ---------------------ERR MESSAGE
    JAVA code------------------it compiles but throw an error when running there -> (*)...
    final String driverClass = "oracle.jdbc.driver.OracleDriver";
    final String connectionURLThin = "jdbc:oracle:thin:@jeffreyh3:1521:CUSTDB";
    final String userID = "scott";
    final String userPassword = "tiger";
    final String queryString = "SELECT" +
    " user " +
    " , TO_CHAR(sysdate, 'DD-MON-YYYY HH24:MI:SS') " +
    "FROM dual";
    public void driverManager() {
    Connection con = null;
    Statement stmt = null;
    ResultSet rset = null;
    try {
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    con = DriverManager.getConnection(connectionURLThin, userID, userPassword); // (*) prob here
    stmt = con.createStatement ();
    rset = stmt.executeQuery(queryString);
    rset.close();
    stmt.close();
    } catch (SQLException e) {e.printStackTrace();
    --------------------JAVA JDK 1.6
    My system ------------------------
    Oracle Database 10g Express Edition Release 10.2.0.1.0 - Product
    PL/SQL Release 10.2.0.1.0 - Production
    CORE 10.2.0.1.0 Production
    TNS for Linux: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production

    Yes, the network connection could not be established. Like the error said.
    What you're asking about is the exact reason, but that could be any number of things and not at all related to code. You could have the wrong host, the wrong port. A firewall could be blocking the outgoing connection, a firewall could be blocking the incoming connection. Etc. etc.

  • Problem while querying from java

    I have a query like this ...
    Select name,description,start_date from Events where TO_CHAR(start_date,'MM/DD/YYYY')='09/19/2004';
    I want to execute the same query using java for which i say
    String QQQ="Select name,description,start_date from Events where TO_CHAR(start_date,'MM/DD/YYYY')='?/?/?'"
    PreparedStatement stmt = conn.prepareStatement(QQQ);
    stmt.setString(1,"09");
    stmt.setString(2,"27");
    stmt.setString(3,"2004");
    But I am not getting the results. Is there anything wrong with the Qusetion marks(?) in the query ?
    I get the results if i directly enter the value for the question mark.
    Please help.
    Thanks.

    Date date = get a Date object somehow, perhaps from SimpleDateFormat.parse()
    String query = "Select name,description,start_date from Events where start_date = ?";
    PreparedStatement ps = con.prepareStatement(query);
    ps.setDate(1, date);
    ps.executeQuery();

  • LDAP Query from Java taking abnormally long

    Is there any reason why this query would take an abnormally long time? When I run the query from the command line it comes back practically instantly, but when I access it via Java it takes close to 30 seconds.
    import java.util.Hashtable;
    import javax.naming.Context;
    import javax.naming.NamingEnumeration;
    import javax.naming.NamingException;
    import javax.naming.directory.Attribute;
    import javax.naming.directory.Attributes;
    import javax.naming.directory.DirContext;
    import javax.naming.directory.InitialDirContext;
    import javax.naming.directory.SearchControls;
    import javax.naming.directory.SearchResult;
    public class LDAPTest {
          * @param args
         public static void main(String[] args) {
              String username = System.getProperty("user.name");
              String LDAPServer = "ldap://ldap.myldapserver.net/";
              //String attribute = "";
              String query = "uid=" +username;
              Hashtable env = new Hashtable();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL, LDAPServer);
            DirContext context = null;
            NamingEnumeration enumeration = null;
              try {
                   context = new InitialDirContext(env);
                SearchControls ctrl = new SearchControls();
                ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
                enumeration = context.search("", query, ctrl);
                //while (enumeration.hasMore()) {
                     SearchResult searchResult = (SearchResult) enumeration.next();
                    Attributes attributes = searchResult.getAttributes();
                    Attribute attr = attributes.get("cn");
                    String cn = (String) attr.get();
                    System.out.println(" Person Common Name = " + cn);
            } catch (NamingException e) {
                throw new RuntimeException(e);
            } finally {
                if (enumeration != null) {
                    try {
                         enumeration.close();
                    } catch (Exception e) {
                if (context != null) {
                    try {
                         context.close();
                    } catch (Exception e) {
    }

    njb7ty wrote:
    One way to speed it up is to only retreive those attributes your interested in via ctls.setReturningAttributes.
    Also, if you know what sub directories you want to look in, you can create a list of just those subdirectories and look through them one at a time via ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    SearchControls ctls = new SearchControls();
    ctls.setReturningAttributes((String[])attrIDs.toArray(new String[attrIDs.size()]));
    //only look at the immediate folder level specified (not in sub-folders)
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);Hi, thanks. I tried these, unfortunately I don't know enough about ldap to set the onelevel_scope properly. I have narrowed it down as a combination of load and login issues. For example, in our test environment the java program returns instantly with anonymous. In our production environment it returns in about 30-40 seconds with no login credentials supplied. (it does allow anonymous access). I made sure I set the authentication to none when attempting to try this. But when I do an anonymous query from the command line via a ldapsearch program it pulls the results instantly. (i know it is anonymous because if I specify credentials it pulls back additional data). For some reason it just takes really long to resolve in our production environment if I try anonymous access and I haven't figured it out yet. When I supply login credentials to our production environment it comes back in under a fifth of a second.

  • How to open a brio Query from Java

    Hi,
    I am working with Hyperion Intellegence Explorer to take care of the MIS related activities, to pull out the Data from the Data Base and Export it to the Excel
    Actually this is a BAU.
    So i want to reduce my work burdon. I am a Java Progrrammer too. So i want to automate all the thing from Java.
    Pls help me below to open a Brio files from Java,so that i can proceed to process the Query and export it on to the Excel.,

    Don't double post the same question. You can continue in your previous thread
    [http://forums.sun.com/thread.jspa?threadID=5367120]
    I'm locking this one and it will be removed it later.
    db

  • To Open a Brio Query from Java

    Hi,
    I am using Hyperian Intellegence Explorer to get a information from the Data Base.
    I want to do it automatic,because this we are doing this as a BAU.
    I want to reduce my work load ,so thatpln to write a Code.
    Please help me how to Open an existing BrioQuery from Java.

    corlettk wrote:
    http://geocities.com/khory_scythe/Praxeum/jedicode.html
    Yeah that fits... except I swear a lot. Is that allowed?
    Jedi use their powers to defend and protect, never to attack others.Can we throw an exception for this one?
    edit: actually i disagree with the whole jedi code, its wrong, wheres the fun...
    Mel

  • XML database query through Java

    Hi all.
    I am collecting information about a little application i am trying to build:
    I have an XML database with records divided in a lot of subdirectory (with three or four .xml files);
    directories' names are defined by date in format "yyyymmdd",
    the file within are "date_something.xml":
    what is the best way to access it by a web app or a java class to search all the dirs adn print results in a readable way (aka not in cmd) ? I need first to define a period of time to search and then some attribute or node to print referred to some element.
    I was guessing to use xpath, anyway I ve tryed JSP but it is too difficult and the query i have to do are really simple to build a full servlet.
    I am learning xalan through servlet and I think in future this will be my choice but now i need to collect the data by queries without any automation, just to have results for researching and paper writing.
    The main problem I found is to search a full series of directory, with transformations i can find out stuff from a single file, but how to do it for a system of directories?
    Any suggestion or link to resource would be good also.

    lm00 wrote:
    ProjectMoon wrote:
    By XML database do you mean an actual XML native database, or just a bunch of XML files in a directory structure? If it is an actual XML native database, you should probably use the XML:DB API. If they are just flat files you will need to probably make something that is able to navigate through your directory structure to the documents you want. Once you have that, you can then use XQuery or XPath to get information from those documents.The data is a bunch of directories named by date in format "yyyymmdd", inside each of these there are three or four files .xml
    All files have data definitions and schemas but i dont think they are a 'database'. What do u mean "something to navigate through"? A class? Suppose I would like to do it as a webapp what should i have to do?
    Yes, I basically meant a class. Before querying the XML file you need something that will retrieve its location. If it's by date you could probably concoct something that takes a Date object and returns a set of File objects. Internally it would traverse the directory trees and find the proper XML file(s).
    >>
    If you have a LOT of XML documents I honestly recommend something like the eXist XML Native Database, or another XND. I have been playing with them lately and they are very useful.in this case what i have to do? Take the data and put it into a database by this tool? And then I should acces it by a JSP? There is a program using Xpath instead?Well, yes. You would put the files in the XND. Although I don't know if that's useful or not in your situation. It all depends. I also think you're a bit confused as to what JSPs and XPath are...
    JSPs are just Java Server Pages, which get dynamically compiled into servlets. If you are following the MVC pattern for servlets/JSP (which you should), JSPs represent your views while servlets are the controllers. The model would be your XML data in this case. XPath is a way to get at that data. If it was in an XND, you could just throw an XQuery/XPath expression at the database and it would give you back XML documents/fragments representing the results of your query. You don't have to make your own system to find the XML documents. Of course, you do have to learn how to use an XND.
    Perhaps you should separate what you are trying to do. You have two problems: 1) how to get the XML data you need. 2) How to present it. You should separate those two completely and learn how to do both before attempting to put it together.
    Edited by: ProjectMoon on Oct 21, 2009 12:05 PM

  • Database query from jsp

    hi! All
    i am making the following query to the MySQL database from a jsp page but I get error. please help.
    i am asking user to type in first few letters of person's first name and i use that string to find the match.
    String getName = request.getParameter("search_name"); // gets the few letters entered by user
    // fname is a field in the Employee table
    rs = statement.excuteQuery("Select fname, lname, from Employee where fname.indexOf('" + getName + "') != -1");
    Thanks in advance

    It looks like you have Java code in your select statement.
    I don't know what database your using but you want something
    like this.
    <%
    String getName = request.getParameter("search_name");
    /* I use ingress for my rdms and in ingress you use the keywork 'like'
       to match against character data. The '%' character is the wild card. So, this
       query looks for fname's that have any number of characters followed
       by the value stored in the java string getName, followed by any
       number of characters. */
    rs = statement.excuteQuery("Select fname, lname, from Employee where fname like '%" + getName + "%'");
    %>-S-

  • Generating database tables from Java classes

    Hi,
    I've encountered a number of tools which will create Java classes from database tables (e.g. JDeveloper has this functionality, Abator provides this for iBATIS, etc...).
    However, I've not been able to locate any tools that perform the opposite job - i.e. given a Java class, it generates a database table (or, presumably, some SQL).
    It's been suggested to me that Hibernate might provide this sort of capability, but if anybody has any experience of doing this, in any tool, I'd be interested to hear about it.
    Thanks,
    Alistair.

    Many thanks for the pointers.
    duffymo: I've taken a look at Middlegen (http://boss.bekk.no/boss/middlegen/index.html) but it seems that the first step is to specify the database schema, whereas I'm looking to generate the schema from existing code. Or have I missed something?
    Alistair.

  • Ms Access query from Java

    I'm trying to finish a program but there are some bugs in accessing the database, the connection opened well and i can retreive any data from the data base but when i wrote this sql statement:
    rs = stmt.executeQuery("Select number,Type, sum(charge) from invoice where date between '" + d1 +"' and '"+ d2 + "' Group By number, Type;");
    an error was appeared with:
    "data type mismatch in criteria expression"
    the d1 and d2 are variables with date datatype
    in invoice table "date" is an attribute with date/time datatype..
    anyone to help me??
    thanks all

    the real problem here that in java d1 and d2 areNo the real problem is your refusal to use Prepared Statements.
    converted from from string to date data type
    so it consists of: dayname, day , month, hour, and
    year
    and in MS Access the date attribute is consist of
    day, month and year only.. If you used Prepared Statements then this would not matter.
    so when i compare these d1and d2 in java with date in
    ms access it cause miss match data type error..
    how to make d1,d2 in the format "dd/mm/yyyy" and
    still date data type???
    USE PREPARED STATEMENTS.
    java.sql.PreparedStatement
    Look that up. Annie gave you an example in her post.

  • How to enable database access from Java or CSharp ?

    I set up an Oracle Express database on my local computer.
    Now I want to connect to this databsee from a CSharp (or Java) program.
    How do I have to specify the connection string?
    The following does NOT work:
    connectionstring = "Data Source=XE;User Id=karl;Password=mypassword";
    connection = new OracleConnection(connectionstring);
    connection.Open();
    I am getting an error
    "Invalid argument" ORA-12532 error
    How do I have to specify the connection string otherwise ?
    Is the sequence of the parameter Data Source, User Id and Password
    important ?
    How do I get a more detailed error message from Oracle ?
    Do I have to enable the accessibility from outside programs
    in Oracle somewhere ?

    about to the error:
    ORA-12532 TNS:invalid argument
    Cause: An internal function received an invalid parameter. This message is not normally visible to the user.
    Action: For further details, turn on tracing and re-execute the operation. If the error persists, contact Oracle Support Services.
    Regards

  • Using mdx query from Java Apache

    Please suggest/guide me how to use MDX query to pull data from cube from Apache JAVA??
    BI GUY

    Hi BIGUY,
    Multidimensional Expressions (MDX) is the query language that you use to work with and retrieve multidimensional data in Microsoft Analysis Services. MDX is based on the XML for Analysis (XMLA) specification, with specific extensions for SQL Server Analysis
    Services.
    According to your description, it's hard to give your the exact MDX query to pull the data which you want from the cube since there are no any detail information about the cube. Here are some basic knowledge for your reference.
    Querying Multidimensional Data with MDX
    MDX Sample
    Regards,
    Charlie Liao
    TechNet Community Support

Maybe you are looking for

  • How do I add new photos to my external back up without duplicating the entire library?

    My iPhoto libraries are a complete mess. I can't be the only person who: a) wants a number of libraries for different types of image (digital art, holiday snaps, etc) b) wants to keep the bulk of his library on an external drive, to free up space on

  • How to make Runtime.exec call Linux exec?

    Howdy, I am trying to use a combination of 'find' and 'rm' to delete all files with a certain extension in a directory and all of its subdirs. Here's the command: Process proc = runtime.exec("find " + dir + " -name '*.vcs' -exec rm -rf {} \\;"); It's

  • Cannot scroll with my keyboard through the fonts (Windows)

    I upgraded to CS4 today and I can't scroll through the fonts properly with my keyboard. Every time I scroll through the list it either gets stuck on a font and I have to open the list and select a new one or it skips over all the fonts and lands near

  • Can you "unsend" audio from Soundtrack?

    Okay, so I sent audio to Soundtrack and removed noise. My producer wanted a clean track for client rough cut. Now I'm ready to export an OMF for ProTools using Automatic Duck. Is there a way to reset the audio that was sent to Soundtrack as though it

  • G5/10.4 not seeing MBP anymore...

    Hi there, I had things all set up perfectly... today the G5 can't see the MBP. I have a wireless network. Internal airport cards on both computers, and a Buffalo wireless router (provided by my husband's employer). The G5 is also hardwired to the rou