1. 程式人生 > >AccessToMySql資料庫的匯入以及java生成.exe檔案

AccessToMySql資料庫的匯入以及java生成.exe檔案

一、AccessToMySql

最近做了一個Access資料庫匯入MySql的小工具,期間遇到諸多問題,這裡小計一下。

表名為cur_rec,共有5個欄位

比較奇葩的是這個表居然是四個欄位的聯合主鍵,要實現的功能為從Access資料庫裡面導一個時間段的資料到Mysql,例如:起始日期:2015-02-27  截止日期:2015-03-02

一開始是準備用ODBC,後來覺得還要配置資料來源,比較麻煩,還有路徑問題(後續會製作成.exe)

於是下載了一個Access_JDBC30.jar的驅動(官網的似乎是需要付費的,下載的驅動包有一個問題就是一次最大能夠讀取1000條資料)

於是乎想到了分頁查詢,使用的時候發現Mysql的分頁語句不能使用,糾結了好久.....

但是在分頁查詢的時候查詢網上資料,一般都是隻有一個主鍵的,最後請教了一下我們的牛人,

什麼都不說了,直接上程式碼:

MysqlTest.java

  1 package com.cn.jpz.mysql;
  2 
  3 import java.awt.EventQueue;
  4 
  5 import javax.swing.JFrame;
  6 import javax.swing.JLabel;
  7 import javax.swing.JOptionPane;
  8 
  9 import java.awt.BorderLayout;
 10 import java.awt.Color;
11 import java.awt.event.ActionEvent; 12 import java.awt.event.ActionListener; 13 import java.sql.Connection; 14 import java.sql.Date; 15 import java.sql.DriverManager; 16 import java.sql.PreparedStatement; 17 import java.sql.ResultSet; 18 import java.sql.SQLException; 19 import java.sql.Statement;
20 import java.text.ParseException; 21 import java.text.SimpleDateFormat; 22 import java.util.ArrayList; 23 import java.util.List; 24 25 import javax.swing.JTextField; 26 import javax.swing.JButton; 27 28 public class MysqlTest { 29 30 private JFrame frame; 31 private JTextField textField; 32 private JTextField textField_1; 33 34 private JButton btnInsert; 35 private String sDriver; 36 private Connection conn; 37 private PreparedStatement pstmt = null; 38 private Statement stmt; 39 private PreparedStatement pst = null; 40 private List<ChildVista> datas = new ArrayList<ChildVista>(); 41 private JButton btnNewButton; 42 43 public static String startDateString; 44 public static String endDateString; 45 public static boolean isValidDate; 46 private JTextField textField_2; 47 private PreparedStatement pst2 = null; 48 private ResultSet rst = null; 49 private ResultSet rs; 50 public static int equipNo; 51 private static final int PAGE_SIZE=1000; 52 53 /** 54 * Launch the application. 55 */ 56 public static void main(String[] args) { 57 EventQueue.invokeLater(new Runnable() { 58 public void run() { 59 try { 60 MysqlTest window = new MysqlTest(); 61 window.frame.setVisible(true); 62 } catch (Exception e) { 63 e.printStackTrace(); 64 } 65 } 66 }); 67 } 68 69 /** 70 * Create the application. 71 */ 72 public MysqlTest() { 73 initialize(); 74 } 75 76 /** 77 * Initialize the contents of the frame. 78 */ 79 private void initialize() { 80 frame = new JFrame(); 81 frame.getContentPane().setBackground(Color.WHITE); 82 frame.setBounds(100, 100, 450, 300); 83 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 84 frame.getContentPane().setLayout(null); 85 86 JLabel lblNewLabel = new JLabel("\u8D77\u59CB\u65E5\u671F\uFF1A"); 87 lblNewLabel.setBounds(24, 69, 69, 15); 88 frame.getContentPane().add(lblNewLabel); 89 90 JLabel lblNewLabel_1 = new JLabel("\u622A\u6B62\u65E5\u671F\uFF1A"); 91 lblNewLabel_1.setBounds(246, 69, 66, 15); 92 frame.getContentPane().add(lblNewLabel_1); 93 94 textField = new JTextField(); 95 textField.setText("2015-02-27"); 96 textField.setBounds(103, 66, 79, 21); 97 frame.getContentPane().add(textField); 98 textField.setColumns(10); 99 100 textField_1 = new JTextField(); 101 textField_1.setText("2015-03-02"); 102 textField_1.setBounds(322, 66, 79, 21); 103 frame.getContentPane().add(textField_1); 104 textField_1.setColumns(10); 105 106 btnInsert = new JButton("\u5F00\u59CB"); 107 btnInsert.addActionListener(new ActionListener() { 108 public void actionPerformed(ActionEvent e) { 109 batchInsertIntoMysql(); 110 } 111 }); 112 btnInsert.setBounds(164, 154, 93, 23); 113 frame.getContentPane().add(btnInsert); 114 115 btnNewButton = new JButton("\u83B7\u53D6\u65E5\u671F"); 116 btnNewButton.addActionListener(new ActionListener() { 117 public void actionPerformed(ActionEvent e) { 118 isValidDate = getDate(); 119 if (isValidDate) { 120 ConnODBC(); 121 getDataFromAccess(); 122 } else { 123 JOptionPane.showMessageDialog(null, "日期、裝置號格式不正確,請重新輸入!!"); 124 } 125 } 126 }); 127 btnNewButton.setBounds(164, 114, 93, 23); 128 frame.getContentPane().add(btnNewButton); 129 130 JLabel lblNewLabel_2 = new JLabel( 131 "\u65E5\u671F\u683C\u5F0F\uFF1A2015-03-20"); 132 lblNewLabel_2.setBounds(24, 23, 129, 21); 133 frame.getContentPane().add(lblNewLabel_2); 134 135 JLabel lblNewLabel_3 = new JLabel( 136 "\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"); 137 lblNewLabel_3.setForeground(Color.MAGENTA); 138 lblNewLabel_3.setBounds(10, 187, 414, 23); 139 frame.getContentPane().add(lblNewLabel_3); 140 141 JLabel lblNewLabel_4 = new JLabel( 142 "\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"); 143 lblNewLabel_4.setForeground(Color.MAGENTA); 144 lblNewLabel_4.setBounds(24, 208, 400, 21); 145 frame.getContentPane().add(lblNewLabel_4); 146 147 JLabel label = new JLabel("\u8BBE\u5907\u53F7\uFF1A"); 148 label.setBounds(203, 26, 54, 15); 149 frame.getContentPane().add(label); 150 151 textField_2 = new JTextField(); 152 textField_2.setText("100"); 153 textField_2.setBounds(272, 23, 66, 21); 154 frame.getContentPane().add(textField_2); 155 textField_2.setColumns(10); 156 157 JLabel lbls = new JLabel("\u8BF7\u8010\u5FC3\u7B49\u5F855s"); 158 lbls.setForeground(Color.MAGENTA); 159 lbls.setBackground(Color.BLUE); 160 lbls.setBounds(267, 118, 93, 19); 161 frame.getContentPane().add(lbls); 162 } 163 164 /** 165 * 獲取mysql連線 166 * 167 * @return 168 */ 169 public Connection getMysqlConn() { 170 sDriver = "com.mysql.jdbc.Driver"; 171 String url = "jdbc:mysql://localhost:3306/vista"; 172 String user = "boctek"; 173 String passwd = "BCERA1688"; 174 try { 175 Class.forName("com.mysql.jdbc.Driver"); 176 conn = DriverManager.getConnection(url, user, passwd); 177 } catch (Exception e1) { 178 e1.printStackTrace(); 179 } 180 return conn; 181 } 182 183 /** 184 * 關閉mysql連線 185 */ 186 public void closeMysqlConn(Connection conn) { 187 try { 188 if (conn != null || !conn.isClosed()) { 189 conn.close(); 190 } 191 } catch (SQLException e) { 192 e.printStackTrace(); 193 } 194 195 } 196 197 // 批量插入資料 198 public boolean batchInsertIntoMysql() { 199 System.out.println("開始插入"); 200 List<ChildVista> initialize = datas; 201 for (ChildVista cv : initialize) { 202 insertToMysql(cv); 203 } 204 return false; 205 206 } 207 208 public void insertToMysql(ChildVista childVista) { 209 conn = getMysqlConn(); 210 try {// 執行資料庫查詢,返回結果 211 String sql = "insert into cur_rec values(?,?,?,?,?)"; 212 pst = conn.prepareStatement(sql); 213 pst.setDate(1, childVista.getTmDate()); 214 pst.setInt(2, childVista.getStan()); 215 pst.setInt(3, childVista.getEquipNo()); 216 pst.setInt(4, childVista.getYcNo()); 217 pst.setString(5, childVista.getData().toString()); 218 pst.execute(); 219 pst.close(); 220 } catch (SQLException e) { 221 System.out.println(e.getMessage()); 222 } finally { 223 // 關閉資料庫連線 224 closeMysqlConn(conn); 225 } 226 } 227 228 /* 229 * // 批量插入資料 public boolean batchInsertIntoMysql() { List<ChildVista> 230 * initialize = datas; try { insertToMysql(initialize); } catch 231 * (ParseException e) { e.printStackTrace(); } return false; 232 * 233 * } 234 * 235 * public void insertToMysql(List<ChildVista> childVista) throws 236 * ParseException { conn = getMysqlConn(); SimpleDateFormat sdf = new 237 * SimpleDateFormat("yyyy-MM-dd"); java.util.Date startDate = 238 * sdf.parse(startDateString); java.util.Date endDate = 239 * sdf.parse(endDateString); 240 * 241 * String deleteSql = "delete from cur_rec where tmdate >= '"+ new 242 * Date(startDate.getTime()) +"' and tmdate <= '"+new 243 * Date(endDate.getTime())+"'"; try { System.out.println(deleteSql); pst = 244 * conn.prepareStatement(deleteSql); pst.executeUpdate(); } catch 245 * (SQLException e1) { e1.printStackTrace(); } 246 * 247 * String sql = "insert into cur_rec values(?,?,?,?,?)"; try {// 248 * 執行資料庫查詢,返回結果 pst = conn.prepareStatement(sql); int count = 0; for (int i 249 * = 0; i < childVista.size(); i++) { ChildVista child = childVista.get(i); 250 * pst.setDate(1, child.getTmDate()); pst.setInt(2, child.getStan()); 251 * pst.setInt(3, child.getEquipNo()); pst.setInt(4, child.getYcNo()); 252 * pst.setString(5, child.getData().toString()); pst.addBatch(); } 253 * pst.executeBatch(); } catch (Exception e) { e.printStackTrace(); } 254 * finally { try{ //關閉步驟3所開啟的state物件 pst.close(); 255 * System.out.println("關閉pst物件"); } catch(SQLException e){} try{ //關閉資料庫連線 256 * conn.close(); System.out.println("關閉sql資料庫連線物件"); } catch(SQLException 257 * e){ 258 * 259 * } } } 260 */ 261 public boolean getDate() { 262 boolean convertSuccess = true; 263 startDateString = textField.getText(); 264 endDateString = textField_1.getText(); 265 String equipNoString = textField_2.getText(); 266 if (startDateString == null || startDateString.length() <= 0 267 || endDateString == null || endDateString.length() <= 0 268 || equipNoString == null || equipNoString.length() <= 0) { 269 JOptionPane.showMessageDialog(null, "日期、裝置號不能為空"); 270 return false; 271 } 272 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 273 format.setLenient(false); 274 try { 275 format.parse(startDateString); 276 format.parse(endDateString); 277 equipNo = Integer.parseInt(equipNoString); 278 } catch (ParseException e) { 279 // TODO Auto-generated catch block 280 convertSuccess = false; 281 e.printStackTrace(); 282 } 283 284 return convertSuccess; 285 } 286 287 public void ConnODBC() { 288 289 // 步驟1:載入驅動程式 290 sDriver = "com.hxtt.sql.access.AccessDriver"; 291 try { 292 Class.forName(sDriver); 293 } catch (Exception e) { 294 System.out.println("無法載入驅動程式"); 295 e.printStackTrace(); 296 297 } 298 System.out.println("步驟1:載入驅動程式--成功!"); 299 conn = null; 300 stmt = null; 301 String sCon = "jdbc:access:///ChildVista.mdb"; 302 303 try { 304 conn = DriverManager.getConnection(sCon); 305 if (conn != null) { 306 System.out.println("步驟2:連線資料庫--成功!"); 307 } 308 // 步驟3:建立JDBC的Statement物件 309 stmt = conn.createStatement(); 310 } catch (SQLException e) { 311 System.out.println("連線錯誤:" + sCon); 312 System.out.println(e.getMessage()); 313 314 } 315 } 316 317 public void getDataFromAccess() { 318 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 319 320 try {// 執行資料庫查詢,返回結果 321 java.util.Date startDate = sdf.parse(startDateString); 322 java.util.Date endDate = sdf.parse(endDateString); 323 // where tmdate between #"+new Date(startDate.getTime())+"# and 324 // #"+new Date(endDate.getTime())+"#" 325 326 //Sql語句 獲取規定時間段內的資料 327 String sSQL = "SELECT count (*) FROM cur_rec where tmdate >= ? and tmdate <= ?"; 328 pst = conn.prepareStatement(sSQL); 329 pst.setDate(1, new Date(startDate.getTime())); 330 pst.setDate(2, new Date(endDate.getTime())); 331 System.out.println(sSQL); 332 rs = pst.executeQuery(); 333 ChildVista childVista; 334 Date date; 335 int count = 0; 336 if (rs.next()) { 337 count = rs.getInt(1); 338 } 339 //獲取分頁 340 int page=count/PAGE_SIZE; 341 page = page +( count % PAGE_SIZE > 0 ? 1 : 0); 342 System.out.println("page"+page); 343 for (int i = 0; i < page; i++) { 344 int s = count - i * PAGE_SIZE; 345 int pageSize = s > PAGE_SIZE ? PAGE_SIZE : s; 346 //Access分頁獲取規定時間段內的資料 347 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)"; 348 //String sql = "SELECT * FROM cur_rec where tmdate >= ? and tmdate <= ?"; 349 pst2 = conn.prepareStatement(sql); 350 pst2.setDate(1, new Date(startDate.getTime())); 351 pst2.setDate(2, new Date(endDate.getTime())); 352 rst =pst2.executeQuery(); 353 while (rst.next()) { 354 date = rst.getDate("tmdate"); 355 childVista = new ChildVista(date, rst.getInt("STA_N"),rst.getInt("EQUIP_NO") + equipNo,rst.getInt("YC_NO"), rst.getBytes("data")); 356 datas.add(childVista); 357 } 358 System.out.println("第"+(i+1)+"次插入資料。。。"); 359 } 360 System.out.println(count + "條"); 361 } catch (SQLException e) { 362 e.printStackTrace(); 363 } catch (ParseException e1) { 364 e1.printStackTrace(); 365 } finally { 366 try { 367 // 關閉步驟3所開啟的state物件 368 rst.close(); 369 pst2.close(); 370 rs.close(); 371 pst.close(); 372 System.out.println("關閉statement物件"); 373 } catch (SQLException e) { 374 } 375 try { 376 // 關閉資料庫連線 377 stmt.close(); 378 conn.close(); 379 System.out.println("關閉資料庫連線物件"); 380 } catch (SQLException e) { 381 382 } 383 } 384 } 385 }

ChildVista.java

 1 /*
 2  * ChildVista 模型
 3  */
 4 public class ChildVista {
 5     public Date tmDate;
 6     public int stan;
 7     public int equipNo;
 8     public int ycNo;
 9     public byte[] data;
10 
11     public ChildVista() {
12         super();
13     }
14 
15     public ChildVista(Date tmDate, int stan, int equipNo, int ycNo, byte[] data) {
16         super();
17         this.tmDate = tmDate;
18         this.stan = stan;
19         this.equipNo = equipNo;
20         this.ycNo = ycNo;
21         this.data = data;
22     }
23 
24     public Date getTmDate() {
25         return tmDate;
26     }
27 
28     public void setTmDate(Date tmDate) {
29         this.tmDate = tmDate;
30     }
31 
32     public int getStan() {
33         return stan;
34     }
35 
36     public void setStan(int stan) {
37         this.stan = stan;
38     }
39 
40     public int getEquipNo() {
41         return equipNo;
42     }
43 
44     public void setEquipNo(int equipNo) {
45         this.equipNo = equipNo;
46     }
47 
48     public int getYcNo() {
49         return ycNo;
50     }
51 
52     public void setYcNo(int ycNo) {
53         this.ycNo = ycNo;
54     }
55 
56     public byte[] getData() {
57         return data;
58     }
59 
60     public void setData(byte[] data) {
61         this.data = data;
62     }
63 
64 }

以上即完成了Access往MySql裡的資料插入。

二、java打包生成.exe(參考ice world的部落格)

前言:

我們都知道Java可以將二進位制程式打包成可執行jar檔案,雙擊這個jar和雙擊exe效果是一樣一樣的,但感覺還是不同。其實將java程式打包成exe也需要這個可執行jar檔案。

準備:

第一步:

eclipse、exe4j

選擇Java資料夾下的Runnable JAR file,點選Next,

點選finish即可。完成了AccessToMySql.jar的匯出

第二步:

將專案打包成exe,這裡要明確一點,並不是把所有的檔案都打包成一個exe,資原始檔是不能包進去的,往下看↓

首先,在任意目錄建立一個資料夾,最好命名和專案名相同,我在D盤建立了一個“AccessToMySql”資料夾,之後將所有的資原始檔以及我們生成的可執 行jar檔案(我的AccessToMySql.jar)都拷貝到這個資料夾裡,lib目錄,如果你怕執行該程式的機器上沒安裝jre,那麼你需 要將自己機器上的jre目錄也拷貝進來,我安裝的jre1.8.0_25,最後的目錄結構:

開啟exe4j,跳過歡迎,直接點選左側導航的第二項,因為我們已經提前將java專案打包成可執行jar檔案了

在彈出視窗,選擇“JAR in EXE mode”,點選“Next”

在新視窗中,為我們的應用取個名稱,之後選擇exe生成目錄(我的D:\AccessToMySql),點選“Next”

為我們要生成的exe取名,如果想生成自定義圖示,那麼選擇你的ico檔案,如果你不想在一臺電腦上執行多個你的程式,你可以勾選“Allow only a single...”,這裡我沒選,點選“Next”

點選綠色“+”,設定程式執行的Class Path,先選擇我們自己的可執行jar檔案(我的AccessToMySql.jar),點選OK

之後點選General中的Main Class選擇按鈕,在彈出視窗中,exe4j會自動搜尋當前Class Path下的全部jar中包含main方法的類,並列出,我這裡是MysqlTest,直接選擇它點選“OK”,程式入口類就設定完成了

點選綠色“+”,然後新增我們所依賴的lib庫,Access_JDBC30.jar,mysql-connector-java-commercial-5.1.30-bin.jar

輸入Java最小Jre版本號,即低於這個版本的Jre無法執行該程式,接著點選“Advanced Options”-“Search sequence”,設定一下我們的JRE,之前說過,如果客戶機上沒裝Jre咋辦?,沒關係我們捆綁一個進去

點選綠色“+”來選擇捆綁的JRE位置

預設,點選“Next”

預設,點選“Next”

預設,點選“Next”

即在D盤的資料夾下生成了我們所需的AccessToMySql.exe