开发者

Java & Local Databases

TL DR; Want some Java help with connecting to a truly local database ( no access to server tech ), or if you can whip up code, that will work. All it has to do is query the DB ( MS Access, although can be changed ), and output a JSON string. See EDIT2 for more specificity.

EDIT: Before anyone says JDBC; I looked through the tutorials ( started reading in depth ), but most of it seems to be geared towards server tech, which I have no access to.

EDIT2: Seems most the answers so far are requiring an installation of some kind which I unfortunately cannot do ( and failed to mention, so I apologize ). However, this is what is currently being used and I would like a solution similar for Java that would make it more cross-browser compatible as opposed to being HTA only (link: https://launchpad.net/accessdb )

Okay, for the long version. I'm trying to make use of a local database to create a desktop style application for work ( and possibly make use of the knowledge for other projects ). The database I can create without a problem ( MS Access 2003, just happens to be quickly available ). Currently I'm using ActiveX scripting to work with the database in a HTML Application (*.HTA file works only with Internet Explorer), I would really like to make this more cross browser ( in the event the company EVER switches to an actual browser ) by using JAVA to access the database, then output the results in JSON to a local variable JavaScript can call and make use of.

Honestly would rather tutorial type info开发者_运维问答rmation as I want to actually learn why this works so I can later modify it to suit my needs. I have Eclipse installed as well as JDK, and can right small programs in Java, so not completely brain dead ( but not far from :P ). I've been working with JavaScript so I can read quite a bit of Java code as it stands ( not the same syntax since they are not related, but the little I do know of Java I can translate back to JS without problem ).

Anyway, any assistance would be greatly appreciated. I can continue developing with ActiveX ( as I know that works on the system and I'm 99% sure they will continue using Internet Explorer, but, would like some flexibility ).


I am not sure I understood your requirements very well, however I did decipher some key points. What I am suggesting will let you deliver a complete working application in a single package (say a JAR) that will not require much (if any) configuration or administration of servers.

Some Required skills:

  • Java programming langauge
  • JDBC, SQL
  • JSP and Servlets (for the Web tier)

I'm trying to make use of a local database to create a desktop style application [...] I Want some Java help with connecting to a truly local database ( no access to server tech )

Datastore

JDBC can be used with any database that has a JDBC driver, which isn't necessarily a database in "network mode", it can be used with embedded databases as well.

Here is an example with Derby in embedded mode:

Java & Local Databases

When an application accesses a Derby database using the Embedded Derby JDBC driver, the Derby engine does not run in a separate process, and there are no separate database processes to start up and shut down. Instead, the Derby database engine runs inside the same Java Virtual Machine (JVM) as the application. So, Derby becomes part of the application just like any other jar file that the application uses. Figure 1 depicts this embedded architecture.

Here are some 100% Java and embeddable databases:

http://www.h2database.com/html/main.html

http://db.apache.org/derby/

http://hsqldb.org/

Web tier

You can also embed a Web server like Jetty.

Jetty has a slogan "Don't deploy your application in Jetty, deploy Jetty in your application". What this means is that as an alternative to bundling your application as a standard WAR to be deployed in Jetty, Jetty is designed to be a software component that can be instantiated and used in a Java program just like any POJO.

Embedding Jetty.

Please note that there are other web servers that you can use this way.


Ok, so you need to serve JSON from a local database, right?

You don't need a server, you can serve web pages directly from your local machine ( you just have to point to localhost )

So, basically ( and I know this won't be complete, but I hope is a good start )

You have to:

  • Install a servlet container ( Tomcat or Jetty ), they are very easy to use.
  • Create a servlet or JSP page to display the data ( JSP are also easy )
  • Create a connection using JDBC to a local database such as Derby
  • Use a library to transform your data into JSON

Install tomcat

( I will describe for UNIX, but it's the same for Windows)

Download it from here and then unzip the file in some directory you like ( eg. /home/you/ or C:\Users\you\ )

Open a terminal and go to the tomcat bin directory and type catalina.sh run that will start tomcat, you need to have Java installed on your system

Open your browser in http://localhost:8080

It should look like this:

Java & Local Databases

Create a JSP file

Next, go to the tomcat webapps directory, it should contain these folders:

ROOT/
docs/
examples/
host-manager/
manager/

Create a new one, for instance your or whatever and inside create a file Hello.jsp with the following:

Hello.jsp
----------
Hello, world

And then open in your browser: http://localhost:8080/your/Hello.jsp

Should look like:

Java & Local Databases

Create a JDBC program

Next, in your webapp your create the directory: WEB-INF/lib and save there the derby JDBC driver, you can get it from here

Modify your Hello.jsp file to create a sample table like this:

<%@page import="java.sql.*, java.util.*"%>
<%!
     public String getData() {
         List list = new ArrayList();
         try {
             Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
             Connection connection = DriverManager.getConnection("jdbc:derby:yourdb;create=true");
             // The first time:
             PreparedStatement pstmt = connection.prepareStatement(
                 "CREATE TABLE PEOPLE\n"+
                 "(PERSON_ID INT NOT NULL GENERATED ALWAYS AS IDENTITY\n"+
                 "    CONSTRAINT PEOPLE_PK PRIMARY KEY, PERSON VARCHAR(26))");
            pstmt.executeUpdate();
            pstmt = connection.prepareStatement("INSERT INTO PEOPLE(PERSON) VALUES('OSCAR')");
            pstmt.executeUpdate();
         } catch( Exception e ) { 
             throw new RuntimeException( e );
         }
         return "";
     }
%>
:)
<%
    getData();
%>

And execute your jsp again by going to localhost:8080/your/Hello.jsp

If you execute it twice the system will tell you the table already exists:

Java & Local Databases

That's ok, we have created the table already.

Use a library to output JSON

Shudown tomcat, but pressing contrl-c

Download and copy to your WEB-INF/lib directory the json-simple jar. You can get it from here

Start tomcat again

Comment the creation code in the JSP and replace it for a SQL query like this:

<%@page import="java.sql.*, java.util.*, org.json.simple.JSONValue"%>

<%!
     public String getData() {
         List list = new ArrayList();
         Connection connection = null;
         try {
             Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
              connection = DriverManager.getConnection("jdbc:derby:yourdb;create=true");
             // The first time:
             //PreparedStatement pstmt = connection.prepareStatement(
             //    "CREATE TABLE PEOPLE\n"+
             //    "(PERSON_ID INT NOT NULL GENERATED ALWAYS AS IDENTITY\n"+
             //    "    CONSTRAINT PEOPLE_PK PRIMARY KEY, PERSON VARCHAR(26))");
            //pstmt.executeUpdate();
            //pstmt = connection.prepareStatement("INSERT INTO PEOPLE(PERSON) VALUES('OSCAR')");
            //pstmt.executeUpdate();
            // execute select the second time
            PreparedStatement psmt = connection.prepareStatement("SELECT person FROM PEOPLE");
            ResultSet rs = psmt.executeQuery();
            while( rs.next() ){
                list.add( rs.getString("person"));
            }
         } catch( Exception e ) { 
             throw new RuntimeException( e );
         } finally {
             if( connection != null ) try {
                 connection.close();
             } catch( Exception e ){}
         }
         return JSONValue.toJSONString(list);
     }
%>
:)
<script>
 var list = <%=
    getData()
%>
</script>

Notice we are using a throw import, and at the end, we change the invocation of the method to put the result in a javascript variable list

When run, the JSP page would look like this ( you'll have to right click to see the HTML source code so see the <script> tag):

Java & Local Databases

I hope you find this useful. I tried to make it extremely simple for you.

IMPORTANT The sample above is full of bad practices, don't code like that ( for instance, creating web apps directly on tomcat webapps folder, or executing SQL directly from JSP page ( not to mention , not closing the resources etc. )

The main idea was to give you enough information to get started.

There are ways to integrate this with eclipse, and to use a SQL visor such as SquirrelSQL client to manipulate the data.

This should be simple enough, I actually downloaded the files and create the test while writing this answer, so it should work.


As a follow up to Oscar...

Here's a simple "Type in the SQL" JSP page, using JSTL (Java Standard Tag Library) tags.

All you need to make this work is toss in the derby.jar library.

Download tomcat from Apache.

Download derby from Apache

cd $TOMCAT_HOME/webapps

mkdir yourapp

cd yourapp

Take the following and put it in index.jsp:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>SQL Fun</title>
    </head>
    <body>
        <h1>Welcome to Derby SQL</h1>
        <!-- Form to prompt for SQL -->
        <form action="index.jsp" method="POST">
            <label for="sql">SQL Text:</label>
            <textarea cols="40" rows="10" name="sql"></textarea>
            <br/>
            <!-- click Execute query to execute a SELECT statement -->
            <input type="submit" name="doquery" value="Execute Query"/>
            <!-- click Execute DDL to execute a CREATE, UPDATE, DROP or DELETE statement -->
            <input type="submit" name="doddl" value="Execute DDL"/>
        </form>
        <c:if test="${!empty param.sql}">
            <!-- param is the default variable with the request parameters -->
            Executing: ${param.sql}
            <br/>
            <!-- This sets up the DB Connection to derby -->
            <sql:setDataSource driver="org.apache.derby.jdbc.EmbeddedDriver"
                url="jdbc:derby:derbyDB;create=true" scope="request"/>

            <c:choose>
                <c:when test="${!empty param.doddl}">
                    <sql:update var="result">
                    ${param.sql}
                    </sql:update>
                    Result = ${result}
                </c:when>
                <c:otherwise>
                    <sql:query var="result">
                    ${param.sql}
                    </sql:query>

                    <table border="1">
                        <!-- column headers -->
                        <tr>
                            <c:forEach var="columnName" items="${result.columnNames}">
                                <th><c:out value="${columnName}"/></th>
                            </c:forEach>
                        </tr>
                        <!-- column data -->
                        <c:forEach var="row" items="${result.rowsByIndex}">
                            <tr>
                                <c:forEach var="column" items="${row}">
                                    <td><c:out value="${column}"/></td>
                                </c:forEach>
                            </tr>
                        </c:forEach>
                    </table>
                </c:otherwise>
            </c:choose>
        </c:if>
    </body>
</html>

mkdir WEB-INF

take the following and put it in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

mkdir WEB-INF/lib

copy the derby.jar in to WEB-INF/lib

You should now have 3 files:

$TOMCAT_HOME/webapps/yourapp/index.jsp $TOMCAT_HOME/webapps/yourapp/WEB-INF/web.xml $TOMCAT_HOME/webapps/yourapp/WEB-INF/lib/derby.jar

Now fire up Tomcat, and point your browser at http://localhost:8080/yourapp

And you'll get this little box to type SQL in to.

Derby will create the DB for you automagically.

With the JSTL and SQL tags you can do all you want from straight JSP.

Is it "best practice" to do everything in JSP? No.

Does it work? Yes.

Is it practical? Yes.

You can always change it later.


You might want to take a look at Apache Derby. Recent JDKs include it as JavaDB. On Windows, you will find it in ProgramFiles/Sun.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜