ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

java-使用可运行的jar嵌入MS Access数据库

2019-11-21 19:12:53  阅读:221  来源: 互联网

标签:swing jar database-connection java ms-access


因此,我的目标是制造一个可运行的罐子.我已经制作了一个使用swing的程序,该程序使用MS Access数据库来获取记录.因此,我使用了绝对路径来引用数据库进行连接.
现在,我打算将该可运行的jar分发给其他人.因此,我认为最好的选择是将MS Access数据库也嵌入jar文件中.但是我不知道该怎么做.我应该在哪里将数据库保留在Project Explorer中?我应该使用相对路径等吗?任何形式的帮助都是可以理解的.

我发现有许多使用Derby数据库的教程,这些教程可以实现相同的内容,但都与Ms Access数据库无关.欢迎提出建议!

这是我的代码:

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();
    }
}

解决方法:

以下内容使用Eclipse和JavaSE-1.7为我工作. Eclipse在其Package Explorer中显示以下内容

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

[C:]
   [Users]
      [Gord]
         [workspace]
            [com.example.jartest]
               [src]
                  [com]
                     [example]
                        [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; 

        // 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();
        }
    }

}

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

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

…并在我的64位Windows开发计算机上通过

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

标签:swing,jar,database-connection,java,ms-access
来源: https://codeday.me/bug/20191121/2054091.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有