Java Solaris 加入 SDN 参与讨论 我的社区 注册说明
 
 
 
 
 
 
Java API 文档中文版
连接 Microsoft Access 数据库
 
By Angelo Cristella, 2/20/08  

在本文中,我们将构建一个应用程序,它可以加载数据库中的数据并将其显示在 JTable 组件 Swing 托管的表格中。同时借助筛选器在数据上执行搜索。应用程序执行 Edit(编辑)、 Cancellation(删除) 和 Inserting(插入)记录操作。本教程旨在向希望将所学知识与 Microsoft Access 一起运用在 NetBeans IDE 中使用 GUI 构建桌面应用程序的初学者,提供数据库管理和应用程序开发的基本认识。

要完成本教程,您需要在计算机上安装以下软件:

  • NetBeans IDE 5.5 或 NetBeans 6.0 (下载)
  • Microsoft Access 数据库

预计时间: 30 分钟

 

 

构建数据库


注意: 使用 SQL 语言描述 MyCustomers.mdb 数据库

“town”的图表结构

CREATE TABLE `town` (
`zip` varchar(5) NOT NULL,
`town` varchar(25) default NULL,
PRIMARY KEY (`zip`)
) ;


INSERT INTO `town` (`zip`, `town`) VALUES
('12340', 'Milano'),
('12341', 'Roma'),
('12342', 'Napoli'),
('12343', 'Bari'),
('12344', 'Bologna');

 

“Customer”的图表结构

CREATE TABLE `customer` (
`code` varchar(5) NOT NULL,
`firstname` varchar(50) default N\ULL,
`name` varchar(50) default NULL,
`date` date default NULL,
`zip` varchar(5) default NULL,
`balance` float default NULL,
PRIMARY KEY (`code`),
KEY `Icap` (`zip`)
) ;



INSERT INTO `customer` (`code`, `firstname`, `name`, `date`, `zip`, `balance`) VALUES
('AAA00', 'Rossi', 'Paolo', '2007-11-12', '12340', 123.5),
('AAA01', 'Bianchi', 'Mariaja', '2007-01-01', '12341', 321),
('AAA02', 'Bianchi', 'Laura', '2007-01-01', '12342', 321),
('AAA03', 'Galli', 'Egidio', '2007-01-10', '12343', 0),
('AAA04', 'Rossi', 'Andrea', '2007-05-05', '12344', 568),
('AAA05', 'McJoy', 'Bill', '2007-04-01', '12340', 145),
('AAA06', 'Skorpy', 'John', '2007-01-21', '12340', 0),
('AAA07', 'Verdi', 'Mario', '2007-01-01', '12344', 125),
('AAA08', 'Mullen', 'Jane', '2007-02-03', '12342', 45),
('AAA09', 'Viola', 'Paola', '2007-04-16', '12341', 574);

约束


ALTER TABLE `customer`
ADD CONSTRAINT FOREIGN KEY (`zip`) REFERENCES `town` (`zip`) ON DELETE CASCADE ON UPDATE CASCADE;

 

 

 

创建新项目


1. 从 File 菜单中选择 New Project 选项 (Ctrl+Maiusc+N)

2. 单击 Next 按钮继续操作

 

构建图形用户界面(GUI)


1. 为项目添加 JFrame 组件:

a. 为组件选择名称,默认名称为 NewJFrame

2. 从 Palette Swing 中向所有其他组件添加 JForm

3. 拖放 Swing beans 用以组装下表:

 

 

4. 在 NewJFrame.java 文件中添加import(导入):

import com.sun.rowset.FilteredRowSetImpl;
import com.sun.rowset.JdbcRowSetImpl;
import java.sql.*;
import javax.sql.RowSet;
import javax.sql.RowSetEvent;
import javax.sql.RowSetListener;
import javax.sql.rowset.FilteredRowSet;
import javax.sql.rowset.JdbcRowSet;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

 

5. 在 NewJframe.java 文件结尾处添加声明:

private String url   = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=MyCustomers.mdb";          
public static FilteredRowSet frs;
private Filter fil;
private NewTabella TabCustomer=new NewTabella();

 

6. 为变量 jScrollPane1 设置修正值 public static :

7. 在 NewJFrame.java 文件中替换构造器:

public NewJFrame() {
initComponents();
}

使用构造器:

public NewJFrame() {
initComponents();
Find.setEnabled(false);
setDefaultLookAndFeelDecorated(true);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
this.pack();
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}

try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException ex) {
ex.printStackTrace(); }
}

 

 

Bean 编程


§ 1: Swing: JButton NameVariable: FilteredRowSetPopola Code for Event: ActionPerformed

FilteredRowSetPopola.setEnabled(false);
Update.setEnabled(true);
Find.setEnabled(true);
Delete.setEnabled(true);
Add.setEnabled(true);
try {
frs=new FilteredRowSetImpl();
frs.setUsername("");
frs.setPassword("");
frs.setUrl(url);
frs.addRowSetListener(TabCustomer);
frs.setCommand("select * from Customers");
frs.execute();
} catch (SQLException ex) {ex.printStackTrace();}

§ 2: Swing: JButton NameVariable: Find Code for Event: ActionPerformed

try {
fil=new Filter(firstname.getText(),zip.getText());
frs.beforeFirst();
frs.setFilter(fil);
frs.rowSetPopulated(new RowSetEvent(frs),1);
} catch (SQLException ex) {ex.printStackTrace();}

§ 5: Swing: JTextField NameVariable: zip

 

 

§ 6: Swing: JTextField NameVariable: firstname

 

 

§ 7: Swing: JTable Nome: TabCustInit

 

§ 8: Swing: JButton NameVariable: Update Enabled: False Code for Event: ActionPerformed

try {
/* ATTENTION: CHECK DATA for code,firstname,name,date,zip,balance */
frs.absolute(TabCustomer.getSelectedRow()+1);
frs.updateString("code",(String)TabCustomer.getValueAt(TabCustomer.getSelectedRow(),0));
frs.updateString("firstName",(String)TabCustomer.getValueAt(TabCustomer.getSelectedRow(),1));
frs.updateString("name",(String)TabCustomer.getValueAt(TabCustomer.getSelectedRow(),2));
Date d=Date.valueOf((TabCustomer.getValueAt(TabCustomer.getSelectedRow(),3).toString()));
frs.updateDate("cdate",d);
frs.updateString("zip",(String)TabCustomer.getValueAt(TabCustomer.getSelectedRow(),4));
frs.updateFloat("balance",(Float)TabCustomer.getValueAt(TabCustomer.getSelectedRow(),5));
frs.updateRow();
frs.acceptChanges();
} catch (SQLException ex) {ex.printStackTrace(); }

 

§ 9: Swing: JButton NameVariable: Add Enabled: False Code for Event: ActionPerformed

Add.setEnabled(false);
Edit.setEnabled(true);
Update.setEnabled(false);
Find.setEnabled(false);
Delete.setEnabled(false);
try {
frs.setCommand("INSERT INTO Customers(code,firstName,name,cdate,zip,balance)
values('AAA99','firstname','name',2007-01-01,'12340',0)");
frs.execute();
frs.acceptChanges();
} catch (SQLException ex) {ex.printStackTrace();}

 

§ 10: Swing: JButton NameVariable: Delete Enabled: False Code for Event: ActionPerformed

try {
frs.absolute(TabCustomer.getSelectedRow()+1);
frs.deleteRow();
frs.acceptChanges();
frs.rowSetPopulated(new RowSetEvent(frs),1);
} catch (SQLException ex) {
ex.printStackTrace();
}

 

§ 11: Swing: JButton NameVariable: Edit Enabled: False Code for Event: ActionPerformed

Add.setEnabled(true);
Edit.setEnabled(false);
Update.setEnabled(true);
Find.setEnabled(true);
Delete.setEnabled(true);
try {
frs=new FilteredRowSetImpl();
frs.setUsername("");
frs.setPassword("");
frs.setUrl(url);
frs.addRowSetListener(TabCustomer);
frs.setCommand("select * from Customers");
frs.execute();
} catch (SQLException ex) {ex.printStackTrace();}

实现类筛选器


1. 向项目添加称作 Filter 的新的 Java 类:

 

2. 在 Filter.java 文件中添加import(导入):

import java.sql.SQLException;
import javax.sql.RowSet;
import javax.sql.rowset.Predicate;

3. 在 Filter.java 文件中的替换代码:

public class Filter{
/** Creates a new instance of Filter */
public Filter() {
}
}

使用这个代码:

public class Filter implements Predicate{
String firstnameSeek;
String zipSeek;

/** Creates a new instance of Filter */
public Filter(String firstname,String zip) {
this.firstnameSeek= firstname;
this.zipSeek=zip;
}

public boolean evaluate(RowSet rs) {
boolean validate=true;
try {
if (rs.getRow()>0) {
if (firstnameSeek.length()>0) validate=firstnameSeek.equalsIgnoreCase(rs.getString("firstname"));
if (zipSeek.length()>0) validate=zipSeek.equalsIgnoreCase(rs.getString("zip")) && validate;
}else validate =false;
} catch (SQLException ex) {ex.printStackTrace(); }
return validate;
}

public boolean evaluate(Object value, int column) throws SQLException {

return true;
}

public boolean evaluate(Object value, String columnName) throws SQLException {

return true;
}


}

 

自定义一个新的 jTable 类


1. 向项目添加名称为 NewTabella 的新的 Java 类:

2. 在 NewTabella.java 文件中添加import(导入):

import java.sql.SQLException;
import javax.sql.RowSetEvent;
import javax.sql.RowSetListener;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

3. 在 NewTabella.java 文件中的替换代码:

public class NewTabella{

/**
* Creates a new instance of NewTabella
*/
public NewTabella() {
}
}

使用这个代码:

public class NewTabella extends JTable implements RowSetListener{


/**
* Creates a new instance of NewTabella
*/
public NewTabella() {
}

public void rowSetChanged(RowSetEvent event) {
Object[] record;
String [] intestazCol=new String [] {"Code", "FirstName", "LastName",
"Date", "Zip", "Balance"};
DefaultTableModel dtm=new DefaultTableModel(intestazCol,0){
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class,
java.lang.Object.class, java.lang.String.class, java.lang.Float.class};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
};
try {
NewJFrame.frs.beforeFirst();
while (NewJFrame.frs.next()){
record=new Object[]{NewJFrame.frs.getString("code"),
NewJFrame.frs.getString("firstName"), NewJFrame.frs.getString("name"),
NewJFrame.frs.getDate("cdate"),NewJFrame.frs.getString("zip"),
NewJFrame.frs.getFloat("balance")};
dtm.addRow(record);
}
} catch (SQLException ex) {ex.printStackTrace();}

this.setModel(dtm);
NewJFrame.jScrollPane1.setViewportView(this);

}

public void rowChanged(RowSetEvent event) {
}

public void cursorMoved(RowSetEvent event) {

}

}

 

 

编译项目!

非常感谢您的关注。