AccessToMySql数据库的导入以及java生成.exe文件

时间:2023-03-09 04:00:47
AccessToMySql数据库的导入以及java生成.exe文件

一、AccessToMySql

最近做了一个Access数据库导入MySql的小工具,期间遇到诸多问题,这里小计一下。

表名为cur_rec,共有5个字段

AccessToMySql数据库的导入以及java生成.exe文件

比较奇葩的是这个表居然是四个字段的联合主键,要实现的功能为从Access数据库里面导一个时间段的数据到Mysql,例如:起始日期:2015-02-27  截止日期:2015-03-02

AccessToMySql数据库的导入以及java生成.exe文件

一开始是准备用ODBC,后来觉得还要配置数据源,比较麻烦,还有路径问题(后续会制作成.exe)

于是下载了一个Access_JDBC30.jar的驱动(官网的似乎是需要付费的,下载的驱动包有一个问题就是一次最大能够读取1000条数据)

于是乎想到了分页查询,使用的时候发现Mysql的分页语句不能使用,纠结了好久.....

但是在分页查询的时候查找网上资料,一般都是只有一个主键的,最后请教了一下我们的牛人,

什么都不说了,直接上代码:

MysqlTest.java

 package com.cn.jpz.mysql;

 import java.awt.EventQueue;

 import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane; import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List; import javax.swing.JTextField;
import javax.swing.JButton; public class MysqlTest { private JFrame frame;
private JTextField textField;
private JTextField textField_1; private JButton btnInsert;
private String sDriver;
private Connection conn;
private PreparedStatement pstmt = null;
private Statement stmt;
private PreparedStatement pst = null;
private List<ChildVista> datas = new ArrayList<ChildVista>();
private JButton btnNewButton; public static String startDateString;
public static String endDateString;
public static boolean isValidDate;
private JTextField textField_2;
private PreparedStatement pst2 = null;
private ResultSet rst = null;
private ResultSet rs;
public static int equipNo;
private static final int PAGE_SIZE=1000; /**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MysqlTest window = new MysqlTest();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} /**
* Create the application.
*/
public MysqlTest() {
initialize();
} /**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.WHITE);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null); JLabel lblNewLabel = new JLabel("\u8D77\u59CB\u65E5\u671F\uFF1A");
lblNewLabel.setBounds(24, 69, 69, 15);
frame.getContentPane().add(lblNewLabel); JLabel lblNewLabel_1 = new JLabel("\u622A\u6B62\u65E5\u671F\uFF1A");
lblNewLabel_1.setBounds(246, 69, 66, 15);
frame.getContentPane().add(lblNewLabel_1); textField = new JTextField();
textField.setText("2015-02-27");
textField.setBounds(103, 66, 79, 21);
frame.getContentPane().add(textField);
textField.setColumns(10); textField_1 = new JTextField();
textField_1.setText("2015-03-02");
textField_1.setBounds(322, 66, 79, 21);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10); btnInsert = new JButton("\u5F00\u59CB");
btnInsert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
batchInsertIntoMysql();
}
});
btnInsert.setBounds(164, 154, 93, 23);
frame.getContentPane().add(btnInsert); btnNewButton = new JButton("\u83B7\u53D6\u65E5\u671F");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
isValidDate = getDate();
if (isValidDate) {
ConnODBC();
getDataFromAccess();
} else {
JOptionPane.showMessageDialog(null, "日期、设备号格式不正确,请重新输入!!");
}
}
});
btnNewButton.setBounds(164, 114, 93, 23);
frame.getContentPane().add(btnNewButton); JLabel lblNewLabel_2 = new JLabel(
"\u65E5\u671F\u683C\u5F0F\uFF1A2015-03-20");
lblNewLabel_2.setBounds(24, 23, 129, 21);
frame.getContentPane().add(lblNewLabel_2); JLabel lblNewLabel_3 = new JLabel(
"\u6CE8\uFF1A\u8F93\u5165\u8D77\u59CB\u65E5\u671F\u548C\u622A\u6B62\u65E5\u671F\u4EE5\u540E\uFF0C\u70B9\u51FB\u83B7\u53D6\u65E5\u671F\uFF0C\u7136\u540E\u70B9\u51FB\u5F00\u59CB");
lblNewLabel_3.setForeground(Color.MAGENTA);
lblNewLabel_3.setBounds(10, 187, 414, 23);
frame.getContentPane().add(lblNewLabel_3); JLabel lblNewLabel_4 = new JLabel(
"\u5219\u5F00\u59CB\u6570\u636E\u7684\u5BFC\u5165\uFF0C\u5F00\u59CB\u6309\u94AE\u6062\u590D\u6B63\u5E38\uFF0C\u6216\u8005\u7A0B\u5E8F\u9000\u51FA\u5219\u5BFC\u5165\u7ED3\u675F");
lblNewLabel_4.setForeground(Color.MAGENTA);
lblNewLabel_4.setBounds(24, 208, 400, 21);
frame.getContentPane().add(lblNewLabel_4); JLabel label = new JLabel("\u8BBE\u5907\u53F7\uFF1A");
label.setBounds(203, 26, 54, 15);
frame.getContentPane().add(label); textField_2 = new JTextField();
textField_2.setText("100");
textField_2.setBounds(272, 23, 66, 21);
frame.getContentPane().add(textField_2);
textField_2.setColumns(10); JLabel lbls = new JLabel("\u8BF7\u8010\u5FC3\u7B49\u5F855s");
lbls.setForeground(Color.MAGENTA);
lbls.setBackground(Color.BLUE);
lbls.setBounds(267, 118, 93, 19);
frame.getContentPane().add(lbls);
} /**
* 获取mysql连接
*
* @return
*/
public Connection getMysqlConn() {
sDriver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/vista";
String user = "boctek";
String passwd = "BCERA1688";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, passwd);
} catch (Exception e1) {
e1.printStackTrace();
}
return conn;
} /**
* 关闭mysql连接
*/
public void closeMysqlConn(Connection conn) {
try {
if (conn != null || !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
} } // 批量插入数据
public boolean batchInsertIntoMysql() {
System.out.println("开始插入");
List<ChildVista> initialize = datas;
for (ChildVista cv : initialize) {
insertToMysql(cv);
}
return false; } public void insertToMysql(ChildVista childVista) {
conn = getMysqlConn();
try {// 执行数据库查询,返回结果
String sql = "insert into cur_rec values(?,?,?,?,?)";
pst = conn.prepareStatement(sql);
pst.setDate(1, childVista.getTmDate());
pst.setInt(2, childVista.getStan());
pst.setInt(3, childVista.getEquipNo());
pst.setInt(4, childVista.getYcNo());
pst.setString(5, childVista.getData().toString());
pst.execute();
pst.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
// 关闭数据库连接
closeMysqlConn(conn);
}
} /*
* // 批量插入数据 public boolean batchInsertIntoMysql() { List<ChildVista>
* initialize = datas; try { insertToMysql(initialize); } catch
* (ParseException e) { e.printStackTrace(); } return false;
*
* }
*
* public void insertToMysql(List<ChildVista> childVista) throws
* ParseException { conn = getMysqlConn(); SimpleDateFormat sdf = new
* SimpleDateFormat("yyyy-MM-dd"); java.util.Date startDate =
* sdf.parse(startDateString); java.util.Date endDate =
* sdf.parse(endDateString);
*
* String deleteSql = "delete from cur_rec where tmdate >= '"+ new
* Date(startDate.getTime()) +"' and tmdate <= '"+new
* Date(endDate.getTime())+"'"; try { System.out.println(deleteSql); pst =
* conn.prepareStatement(deleteSql); pst.executeUpdate(); } catch
* (SQLException e1) { e1.printStackTrace(); }
*
* String sql = "insert into cur_rec values(?,?,?,?,?)"; try {//
* 执行数据库查询,返回结果 pst = conn.prepareStatement(sql); int count = 0; for (int i
* = 0; i < childVista.size(); i++) { ChildVista child = childVista.get(i);
* pst.setDate(1, child.getTmDate()); pst.setInt(2, child.getStan());
* pst.setInt(3, child.getEquipNo()); pst.setInt(4, child.getYcNo());
* pst.setString(5, child.getData().toString()); pst.addBatch(); }
* pst.executeBatch(); } catch (Exception e) { e.printStackTrace(); }
* finally { try{ //关闭步骤3所开启的state对象 pst.close();
* System.out.println("关闭pst对象"); } catch(SQLException e){} try{ //关闭数据库连接
* conn.close(); System.out.println("关闭sql数据库连接对象"); } catch(SQLException
* e){
*
* } } }
*/
public boolean getDate() {
boolean convertSuccess = true;
startDateString = textField.getText();
endDateString = textField_1.getText();
String equipNoString = textField_2.getText();
if (startDateString == null || startDateString.length() <= 0
|| endDateString == null || endDateString.length() <= 0
|| equipNoString == null || equipNoString.length() <= 0) {
JOptionPane.showMessageDialog(null, "日期、设备号不能为空");
return false;
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
format.setLenient(false);
try {
format.parse(startDateString);
format.parse(endDateString);
equipNo = Integer.parseInt(equipNoString);
} catch (ParseException e) {
// TODO Auto-generated catch block
convertSuccess = false;
e.printStackTrace();
} return convertSuccess;
} public void ConnODBC() { // 步骤1:加载驱动程序
sDriver = "com.hxtt.sql.access.AccessDriver";
try {
Class.forName(sDriver);
} catch (Exception e) {
System.out.println("无法加载驱动程序");
e.printStackTrace(); }
System.out.println("步骤1:加载驱动程序--成功!");
conn = null;
stmt = null;
String sCon = "jdbc:access:///ChildVista.mdb"; try {
conn = DriverManager.getConnection(sCon);
if (conn != null) {
System.out.println("步骤2:连接数据库--成功!");
}
// 步骤3:建立JDBC的Statement对象
stmt = conn.createStatement();
} catch (SQLException e) {
System.out.println("连接错误:" + sCon);
System.out.println(e.getMessage()); }
} public void getDataFromAccess() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try {// 执行数据库查询,返回结果
java.util.Date startDate = sdf.parse(startDateString);
java.util.Date endDate = sdf.parse(endDateString);
// where tmdate between #"+new Date(startDate.getTime())+"# and
// #"+new Date(endDate.getTime())+"#" //Sql语句 获取规定时间段内的数据
String sSQL = "SELECT count (*) FROM cur_rec where tmdate >= ? and tmdate <= ?";
pst = conn.prepareStatement(sSQL);
pst.setDate(1, new Date(startDate.getTime()));
pst.setDate(2, new Date(endDate.getTime()));
System.out.println(sSQL);
rs = pst.executeQuery();
ChildVista childVista;
Date date;
int count = 0;
if (rs.next()) {
count = rs.getInt(1);
}
//获取分页
int page=count/PAGE_SIZE;
page = page +( count % PAGE_SIZE > 0 ? 1 : 0);
System.out.println("page"+page);
for (int i = 0; i < page; i++) {
int s = count - i * PAGE_SIZE;
int pageSize = s > PAGE_SIZE ? PAGE_SIZE : s;
//Access分页获取规定时间段内的数据
String sql = "SELECT TOP "+pageSize+" * FROM( SELECT * FROM (SELECT TOP "+PAGE_SIZE*(i+1)+" * FROM cur_rec where tmdate >= ? and tmdate <= ? ORDER BY tmdate DESC,STA_N DESC,EQUIP_NO DESC,YC_NO DESC) ORDER BY tmdate,STA_N,EQUIP_NO,YC_NO)";
//String sql = "SELECT * FROM cur_rec where tmdate >= ? and tmdate <= ?";
pst2 = conn.prepareStatement(sql);
pst2.setDate(1, new Date(startDate.getTime()));
pst2.setDate(2, new Date(endDate.getTime()));
rst =pst2.executeQuery();
while (rst.next()) {
date = rst.getDate("tmdate");
childVista = new ChildVista(date, rst.getInt("STA_N"),rst.getInt("EQUIP_NO") + equipNo,rst.getInt("YC_NO"), rst.getBytes("data"));
datas.add(childVista);
}
System.out.println("第"+(i+1)+"次插入数据。。。");
}
System.out.println(count + "条");
} catch (SQLException e) {
e.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
} finally {
try {
// 关闭步骤3所开启的state对象
rst.close();
pst2.close();
rs.close();
pst.close();
System.out.println("关闭statement对象");
} catch (SQLException e) {
}
try {
// 关闭数据库连接
stmt.close();
conn.close();
System.out.println("关闭数据库连接对象");
} catch (SQLException e) { }
}
}
}

ChildVista.java

 /*
* ChildVista 模型
*/
public class ChildVista {
public Date tmDate;
public int stan;
public int equipNo;
public int ycNo;
public byte[] data; public ChildVista() {
super();
} public ChildVista(Date tmDate, int stan, int equipNo, int ycNo, byte[] data) {
super();
this.tmDate = tmDate;
this.stan = stan;
this.equipNo = equipNo;
this.ycNo = ycNo;
this.data = data;
} public Date getTmDate() {
return tmDate;
} public void setTmDate(Date tmDate) {
this.tmDate = tmDate;
} public int getStan() {
return stan;
} public void setStan(int stan) {
this.stan = stan;
} public int getEquipNo() {
return equipNo;
} public void setEquipNo(int equipNo) {
this.equipNo = equipNo;
} public int getYcNo() {
return ycNo;
} public void setYcNo(int ycNo) {
this.ycNo = ycNo;
} public byte[] getData() {
return data;
} public void setData(byte[] data) {
this.data = data;
} }

以上即完成了Access往MySql里的数据插入。

二、java打包生成.exe(参考ice world的博客)

前言:

我们都知道Java可以将二进制程序打包成可执行jar文件,双击这个jar和双击exe效果是一样一样的,但感觉还是不同。其实将java程序打包成exe也需要这个可执行jar文件。

准备:

第一步:

eclipse、exe4j

AccessToMySql数据库的导入以及java生成.exe文件

选择Java文件夹下的Runnable JAR file,点击Next,

AccessToMySql数据库的导入以及java生成.exe文件

点击finish即可。完成了AccessToMySql.jar的导出

第二步:

将项目打包成exe,这里要明确一点,并不是把所有的文件都打包成一个exe,资源文件是不能包进去的,往下看↓

首先,在任意目录创建一个文件夹,最好命名和项目名相同,我在D盘创建了一个“AccessToMySql”文件夹,之后将所有的资源文件以及我们生成的可执 行jar文件(我的AccessToMySql.jar)都拷贝到这个文件夹里,lib目录,如果你怕执行该程序的机器上没安装jre,那么你需 要将自己机器上的jre目录也拷贝进来,我安装的jre1.8.0_25,最后的目录结构:

AccessToMySql数据库的导入以及java生成.exe文件

打开exe4j,跳过欢迎,直接点击左侧导航的第二项,因为我们已经提前将java项目打包成可执行jar文件了

AccessToMySql数据库的导入以及java生成.exe文件

在弹出窗口,选择“JAR in EXE mode”,点击“Next”

AccessToMySql数据库的导入以及java生成.exe文件

在新窗口中,为我们的应用取个名称,之后选择exe生成目录(我的D:\AccessToMySql),点击“Next”

AccessToMySql数据库的导入以及java生成.exe文件

为我们要生成的exe取名,如果想生成自定义图标,那么选择你的ico文件,如果你不想在一台电脑上运行多个你的程序,你可以勾选“Allow only a single...”,这里我没选,点击“Next”

AccessToMySql数据库的导入以及java生成.exe文件

点击绿色“+”,设置程序运行的Class Path,先选择我们自己的可执行jar文件(我的AccessToMySql.jar),点击OK

AccessToMySql数据库的导入以及java生成.exe文件

之后点击General中的Main Class选择按钮,在弹出窗口中,exe4j会自动搜索当前Class Path下的全部jar中包含main方法的类,并列出,我这里是MysqlTest,直接选择它点击“OK”,程序入口类就设置完成了

AccessToMySql数据库的导入以及java生成.exe文件

点击绿色“+”,然后添加我们所依赖的lib库,Access_JDBC30.jar,mysql-connector-java-commercial-5.1.30-bin.jar

AccessToMySql数据库的导入以及java生成.exe文件

输入Java最小Jre版本号,即低于这个版本的Jre无法运行该程序,接着点击“Advanced Options”-“Search sequence”,设置一下我们的JRE,之前说过,如果客户机上没装Jre咋办?,没关系我们捆绑一个进去

AccessToMySql数据库的导入以及java生成.exe文件

点击绿色“+”来选择捆绑的JRE位置

AccessToMySql数据库的导入以及java生成.exe文件

默认,点击“Next”

AccessToMySql数据库的导入以及java生成.exe文件

默认,点击“Next”

AccessToMySql数据库的导入以及java生成.exe文件

默认,点击“Next”

AccessToMySql数据库的导入以及java生成.exe文件

即在D盘的文件夹下生成了我们所需的AccessToMySql.exe

AccessToMySql数据库的导入以及java生成.exe文件