使用runnable jar嵌入MS Access数据库 [英] embed MS Access database with runnable jar

查看:249
本文介绍了使用runnable jar嵌入MS Access数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的目标是制作一个可运行的jar。我做了一个程序使用swings,使用MS Access数据库获取记录。所以,我使用绝对路径来引用数据库进行连接。
现在,我打算将这个可运行的jar分发给其他人。所以我想最好的选择是嵌入MS Access数据库以及在jar文件。但我不知道该怎么做。我应该在我的项目资源管理器中保存数据库?我应该使用相对路径等。任何形式的帮助将是明显的。



我发现了许多教程使用Derby数据库,将实现相同,但没有属于Ms数据库。欢迎提出建议!



这是我的代码: -

  import java.awt。*; 
import java.awt.event。*;
import java.sql。*;
import java.util.Vector;

import javax.swing。*;
import javax.swing.table.DefaultTableModel;

public class r_search extends JFrame implements ActionListener {

JFrame frame1;
JLabel l0,l1,l2;
JComboBox c1;
JButton b1;
Connection con;
ResultSet rs,rs1;
语句st,st1;
PreparedStatement pst;
String ids;
static JTable table;
String [] columnNames = {SECTION NAME,REPORT NAME,CONTACT,LINK};
String from;






r_search(){

l0 = new JLabel(Fetching Search Results。 ..);
l0.setForeground(Color.blue);
l0.setFont(new Font(Serif,Font.BOLD,20));
l1 = new JLabel(Search);
b1 = new JButton(submit);

l0.setBounds(100,50,350,40);
l1.setBounds(75,110,75,20);
b1.setBounds(150,150,150,20);
b1.addActionListener(this);

setTitle(Search Executive Reports :));
setLayout(null);
// setVisible(true);
setSize(500,500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

add(l0);
add(l1);;
add(b1);
try {
Vector v = new Vector();
String url =jdbc:odbc:Driver = {Microsoft Access Driver(* .mdb,* .accdb)}; DBQ =+C:\\users \\ppreeti\\ executive_db.accdb;
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
con = DriverManager.getConnection(url,,);
/ * con = DriverManager.getConnection(jdbc:oracle:thin:@ mcndesktop07:1521:xe,sandeep,welcome); * /
st = con.createStatement
rs = st.executeQuery(select Index_name from Index1);
// Vector v = new Vector();
while(rs.next()){
ids = rs.getString(1);
v.add(ids);
}
c1 = new JComboBox(v);
c1.setBounds(150,110,150,20);

add(c1);
st.close();
rs.close();
} catch(Exception e){
}
setVisible(true);
}

public void actionPerformed(ActionEvent ae){
if(ae.getSource()== b1){
showTableData();
}

}

public void showTableData(){

frame1 = new JFrame(Database Search Result);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLayout(new BorderLayout());
// TableModel tm = new TableModel();
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
// DefaultTableModel model = new DefaultTableModel(tm.getData1(),tm.getColumnNames());
// table = new JTable(model);
table = new JTable();
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
scroll.setHorizo​​ntalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_​​AS_NEEDED);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_​​AS_NEEDED);
from =(String)c1.getSelectedItem();
// String textvalue = textbox.getText();
String uname =;
String email =;
String pass =;
String cou =;

try {
/ * pst = con.prepareStatement(select * from emp where UNAME ='+ from +'); * /
pst = con。 prepareStatement(select distinct Section.Section_Name,Report.Report_Name,Report.Link,Contact.Contact_Name
+FROM((INNER JOIN报告Report.Section_ID = Section.Section_ID)INNER JOIN联系ON Contact.Contact_ID = Report.Contact_ID)LEFT JOIN指标ON Metrics.Report_ID = Report.Report_ID
+WHERE Section.Section_Name LIKE'%+ from +%OR Report.Report_Name LIKE'%+ from +%OR Metrics.Metric_Name LIKE'%+ from +%'OR Contact.Contact_Name LIKE'%+ from +%');
ResultSet rs = pst.executeQuery();
int i = 0;
while(rs.next()){
uname = rs.getString(Section_Name);
email = rs.getString(Report_Name);
pass = rs.getString(Contact_Name);
cou = rs.getString(Link);
model.addRow(new Object [] {uname,email,pass,cou});
i ++;
}
if(i <1){
JOptionPane.showMessageDialog(null,No Record Found,Error,JOptionPane.ERROR_MESSAGE);
}
if(i == 1){
System.out.println(i +Record Found);
} else {
System.out.println(i +Records Found);
}
} catch(Exception ex){
JOptionPane.showMessageDialog(null,ex.getMessage(),Error,JOptionPane.ERROR_MESSAGE);
}
frame1.add(scroll);
frame1.setVisible(true);
frame1.setSize(1000,400);
}

public static void main(String args []){
new r_search();
}
}


解决方案

下面为我​​使用Eclipse和JavaSE-1.7工作。 Eclipse在其包资源管理器中显示以下内容





我的项目文件夹中的[文件夹]和文件是

  [C:] 
[users]
[Gord]
[workspace]
[com.example.jartest]
[ src]
[com]
[示例]
[jartest]
JarTestMain.java
[resources]
JarData.mdb



JarTestMain.java中的Java代码是

  package com.example.jartest; 

import java.io. *;
import java.nio.file。*;
import java.sql。*;

public class JarTestMain {

public static void main(String [] args){
String mdbFileName =JarData.mdb;
String tempDbPath = System.getenv(TEMP)。replace('\\','/')+/+ mdbFileName;

//从JAR文件中检索.mdb数据库并保存到%TEMP%文件夹
InputStream strmIn = JarTestMain.class.getResourceAsStream(resources /+ mdbFileName);
File f = new File(tempDbPath);
try {
Files.copy(strmIn,f.toPath(),StandardCopyOption.REPLACE_EXISTING);
} catch(IOException e){
e.printStackTrace();
}

//打开%TEMP%文件夹中的数据库副本并从其表中读取
String connectionString =
jdbc:odbc:Driver = { Microsoft Access驱动程序(* .mdb)}; +
DBQ =+ tempDbPath;
try(Connection con = DriverManager.getConnection(connectionString)){
语句s = con.createStatement();
ResultSet rs = s.executeQuery(SELECT * FROM Table1);
while(rs.next()){
System.out.println(String.format(
%d:%s,
rs.getInt(ID ),
rs.getString(TextField)));
}
rs.close();
con.close()
f.delete();
} catch(Exception e){
e.printStackTrace();
}
}

}

将项目导出到名为JarTest.jar的Runnable JAR文件。我可以在我的32位Windows测试机上使用...运行它。

 C:\Program Files\Java\jre7\bin\java-jar JarTest.jar 

...在我的64位Windows开发机上通过

   


So my aim is to make a runnable jar. I've made a program using swings which uses MS Access database to fetch records. So, I've used an absolute path to refer to the database for connection. Now, I intend to distribute this runnable jar to other people as well. So I guess the best option would be to embed the MS Access database as well in the jar file. But I don't know how to do that. Where should I keep the database in my Project Explorer ? Should I use a relative path etc. Any form of help would be appreciable.

I've found many tutorials for using Derby database that would implement the same but none pertaining to Ms Access database. Suggestions are welcome !

This is my code:-

import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Vector;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class r_search extends JFrame implements ActionListener {

    JFrame frame1;
    JLabel l0, l1, l2;
    JComboBox c1;
    JButton b1;
    Connection con;
    ResultSet rs, rs1;
    Statement st, st1;
    PreparedStatement pst;
    String ids;
    static JTable table;
    String[] columnNames = {"SECTION NAME", "REPORT NAME", "CONTACT", "LINK"};
    String from;






    r_search() {

        l0 = new JLabel("Fetching Search Results...");
        l0.setForeground(Color.blue);
        l0.setFont(new Font("Serif", Font.BOLD, 20));
        l1 = new JLabel("Search");
        b1 = new JButton("submit");

        l0.setBounds(100, 50, 350, 40);
        l1.setBounds(75, 110, 75, 20);
        b1.setBounds(150, 150, 150, 20);
        b1.addActionListener(this);

        setTitle("Search Executive Reports :) ");
        setLayout(null);
        //setVisible(true);
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        add(l0);
        add(l1);;
        add(b1);
        try {
            Vector v = new Vector();
            String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\users\\ppreeti\\executive_db.accdb";
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            con=DriverManager.getConnection(url,"","");
            /*con = DriverManager.getConnection("jdbc:oracle:thin:@mcndesktop07:1521:xe", "sandeep", "welcome");*/
            st = con.createStatement();
            rs = st.executeQuery("select index_name from Index1");
           // Vector v = new Vector();
            while (rs.next()) {
                ids = rs.getString(1);
                v.add(ids);
            }
            c1 = new JComboBox(v);
            c1.setBounds(150, 110, 150, 20);

            add(c1);
            st.close();
            rs.close();
        } catch (Exception e) {
        }
        setVisible(true);
    }

    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == b1) {
            showTableData();
        }

    }

    public void showTableData() {

        frame1 = new JFrame("Database Search Result");
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame1.setLayout(new BorderLayout());
//TableModel tm = new TableModel();
        DefaultTableModel model = new DefaultTableModel();
        model.setColumnIdentifiers(columnNames);
//DefaultTableModel model = new DefaultTableModel(tm.getData1(), tm.getColumnNames());
//table = new JTable(model);
        table = new JTable();
        table.setModel(model);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        table.setFillsViewportHeight(true);
        JScrollPane scroll = new JScrollPane(table);
        scroll.setHorizontalScrollBarPolicy(
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroll.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        from = (String) c1.getSelectedItem();
//String textvalue = textbox.getText();
        String uname = "";
        String email = "";
        String pass = "";
        String cou = "";

        try {
           /* pst = con.prepareStatement("select * from emp where UNAME='" + from + "'");*/
             pst = con.prepareStatement("select distinct Section.Section_Name,Report.Report_Name,Report.Link,Contact.Contact_Name "
                        + "FROM (( Section INNER JOIN Report ON Report.Section_ID=Section.Section_ID ) INNER JOIN Contact ON Contact.Contact_ID=Report.Contact_ID )  LEFT JOIN Metrics ON Metrics.Report_ID=Report.Report_ID  "
                        + " WHERE Section.Section_Name LIKE '%"+from+"%' OR Report.Report_Name LIKE '%"+from+"%' OR Metrics.Metric_Name LIKE '%"+from+"%' OR Contact.Contact_Name LIKE '%"+from+"%' ");
            ResultSet rs = pst.executeQuery();
            int i = 0;
            while (rs.next()) {
                uname = rs.getString("Section_Name");
                email = rs.getString("Report_Name");
                pass = rs.getString("Contact_Name");
                cou = rs.getString("Link");
                model.addRow(new Object[]{uname, email, pass, cou});
                i++;
            }
            if (i < 1) {
                JOptionPane.showMessageDialog(null, "No Record Found", "Error", JOptionPane.ERROR_MESSAGE);
            }
            if (i == 1) {
                System.out.println(i + " Record Found");
            } else {
                System.out.println(i + " Records Found");
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
        frame1.add(scroll);
        frame1.setVisible(true);
        frame1.setSize(1000, 400);
    }

    public static void main(String args[]) {
        new r_search();
    }
}

解决方案

The following worked for me using Eclipse and JavaSE-1.7. Eclipse shows the following in its Package Explorer

The [folders] and files in my project folder are

[C:]
   [Users]
      [Gord]
         [workspace]
            [com.example.jartest]
               [src]
                  [com]
                     [example]
                        [jartest]
                           JarTestMain.java
                           [resources]
                              JarData.mdb

The Java code in JarTestMain.java is

package com.example.jartest;

import java.io.*;
import java.nio.file.*;
import java.sql.*;

public class JarTestMain {

    public static void main(String[] args) {
        String mdbFileName = "JarData.mdb";
        String tempDbPath = System.getenv("TEMP").replace('\\', '/') + "/" + mdbFileName; 

        // retrieve .mdb database from the JAR file and save to %TEMP% folder
        InputStream strmIn = JarTestMain.class.getResourceAsStream("resources/" + mdbFileName);
        File f = new File(tempDbPath);
        try {
            Files.copy(strmIn, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // open the copy of the database in %TEMP% folder and read from its table
        String connectionString = 
                "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};" +
                "DBQ=" + tempDbPath;
        try (Connection con = DriverManager.getConnection(connectionString)) {
            Statement s = con.createStatement();
            ResultSet rs = s.executeQuery("SELECT * FROM Table1");
            while (rs.next()) {
                System.out.println(String.format(
                        "%d: %s", 
                        rs.getInt("ID"), 
                        rs.getString("TextField")));
            }
            rs.close();
            con.close();
            f.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

After I exported the project to a "Runnable JAR file" named JarTest.jar I was able to run it on my 32-bit Windows test machine using...

"C:\Program Files\Java\jre7\bin\java" -jar JarTest.jar

...and on my 64-bit Windows development machine via

"C:\Program Files (x86)\Java\jre7\bin\java" -jar JarTest.jar

这篇关于使用runnable jar嵌入MS Access数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆