javafx學習之資料庫操作
上次我們學習的javafx連線資料庫的簡單操作,這次我們來做一個稍為複雜的操作資料庫示例.IDE是:netbeans 6 beat 2,資料庫用javaDB(jdb6自帶有javaDB資料庫,netbeans 6也帶有,本例使用IDE自帶的javaDB),由於水平問題中文只註解了部份程式碼,請見諒.(如出錯,請把中文註解刪除)
import javafx.ui.*;
import java.lang.Thread;
import java.lang.Exception;
import java.sql.*;
import org.apache.derby.jdbc.*;
// Connect to database
public class Database {
public attribute driverName: String;
public attribute jdbcUrl : String;
public attribute user : String;
public attribute password : String;
public attribute driver : Driver;
public attribute conn : Connection;
public operation connect();
public operation shutdown();
public operation tableExists(table: String);
}// Database
attribute Database.conn = null;
//-------------------------連線資料庫-----------------------------------
operation Database.connect() {
// Load driver class using context class loader
// 載入驅動
var thread = Thread.currentThread();
var classLoader = thread.getContextClassLoader();
var driverClass = classLoader.loadClass(this.driverName);
// Instantiate and register JDBC driver
//例項並註冊驅動
this.driver = (Driver) driverClass.instantiate(); // JavaFX Class
DriverManager.registerDriver(driver);
// Connect to database
//連線資料庫
this.conn = DriverManager.getConnection(this.jdbcUrl, this.user, this.password);
}// Database.connect
//--------------------關閉資源---------------------------
operation Database.shutdown() {
var stmt: Statement = null;
if(null <> this.conn) {
try {
stmt = this.conn.createStatement();
stmt.close();
} catch(e:SQLException) {
e.printStackTrace();
} finally {
if(null <> stmt) {stmt.close();}
this.conn.close();
}
}// if(null <> stmt)
}// operation.Database.shutdown
operation Database.tableExists(table: String)
{
// Check if table exists
//檢查表是否存在,注意這裡並沒有主動去刪除
var tableExists = false;
var dbmd = this.conn.getMetaData();
var rs = dbmd.getTables(null, null, '%', ['TABLE']);
while(rs.next()) {
if(table == rs.getString(3)) {
tableExists = true;
break;
}
}// while(rs.next())
return tableExists;
}// tableExists
// Single userName in the Todo list
class userName {
attribute id : Number;
attribute userName: String;
}// userName
// Todo list
class TODO {
attribute userNames : userName*;
attribute selecteduserName: Number;
attribute newuserName : String;
attribute conn : Connection;
attribute usedb : Boolean;
}// TODO
TODO.conn = null;
TODO.usedb = true;
//---------------------------資料插入---------------------------
trigger on insert userName into TODO.userNames {
// TODO: Remove userName from ListBox if an error occurs
if(this.usedb) {
try {
var stmt: Statement = this.conn.createStatement();
this.conn.setAutoCommit(false);
// Insert new userName in database
//往資料庫插入一條記錄
var rows = stmt.executeUpdate("INSERT INTO Uuser (userName) VALUES('{userName.userName}')");
println("INSERT rows: {rows} for {userName.userName}");
// Get userName of the userName from database
//從資料庫得到userName
var rs = stmt.executeQuery('SELECT userName FROM Uuser');
if(rs.next()) {
userName.userName = rs.getString(1);
this.conn.commit();
}// if(rs.next())
} catch(e:SQLException){
//以對話方塊的形式彈出異常
MessageDialog {
messageType: ERROR//訊息內型
title : "TODO - Add userName"//標題
message : "SQL: {e.getMessage()}"//訊息體
visible : true//可見
}// MessageDialog
} finally {
this.conn.setAutoCommit(true);//自動提交
}
}// if(this.usedb)
}// trigger on insert userName
//---------------------------資料刪除------------------------------------
trigger on delete userName from TODO.userNames {
// TODO: Insert userName again in ListBox if an error occurs
if(this.usedb) {
try {
var stmt: Statement = this.conn.createStatement();
//從資料庫刪除一條記錄
var rows = stmt.executeUpdate("DELETE FROM Uuser WHERE userName = '{userName.userName}'");
println("DELETE rows: {rows} for {userName.userName}");
} catch(e:SQLException) {
MessageDialog {
messageType: ERROR
title : "TODO - Delete userName"
message : "SQL: {e.getMessage()}"
visible : true
}// MessageDialog
}
}// if(this.usedb)
}// trigger on delete
// Database vars
var db : Database = null;
var stmt: Statement = null;
var rs : ResultSet = null;
var rows: Number;
db = Database{driverName: 'org.apache.derby.jdbc.ClientDriver'//資料庫驅動類
jdbcUrl : 'jdbc:derby://localhost:1527/sample'//資料庫連線url
user : 'app'//使用者名稱
password : 'app'};//密碼
var model = TODO {
conn: bind lazy db.conn
};
//-------------------------------建立表----------------------------
try {
// Connect to database
db.connect();
stmt = db.conn.createStatement();
// Create table
//建立表,並插入兩條記錄
if(not db.tableExists('Uuser'))
{
rows = stmt.executeUpdate("CREATE TABLE Uuser(id INT , userName VARCHAR(50))");
println("CREATE TABLE rows: {rows}");
rows = stmt.executeUpdate("INSERT INTO Uuser VALUES(1, 'do')");
println("INSERT rows: {rows}");
rows = stmt.executeUpdate("INSERT INTO Uuser VALUES(2, 'did')");
println("INSERT rows: {rows}");
}// if(not db.tableExists('Uuser'))
// Get userNames from database and add userNames to model.userNames (ListBox)
model.usedb = false;
//從資料庫讀取記錄,並插入到model.userNames(其實就是顯示在listBox)
var rs = stmt.executeQuery("SELECT * FROM Uuser ORDER BY id ASC");
while(rs.next()) {
println("id: {rs.getInt('id')} userName: {rs.getString('userName')}");
insert userName{id: rs.getInt('id') userName: rs.getString('userName')} into model.userNames;
}
model.usedb = true;
//--------------------------面板-----------------------------
Frame {
title : "TODO list with JFXTrigger Example"
onClose: function() {
return db.shutdown();//面板關閉,關閉資料庫相關資源
}
content: BorderPanel {
center: ListBox {
selection: bind model.selecteduserName
cells : bind foreach (userName in model.userNames)
ListCell {
text: userName.userName
}
}// ListBox
bottom: FlowPanel {
content: [
TextField {
columns: 30
value : bind model.newuserName
}, // TextField
//增加按鈕,點選增加一條記錄
Button {
text : 'Add'
enabled: bind model.newuserName.length() > 0
action : operation() {
insert userName{userName: model.newuserName} into model.userNames;
model.newuserName = '';
}
}, // Button
//刪除按鈕,點選刪除一條記錄
Button {
text : 'Delete'
enabled: bind sizeof model.userNames > 0
action : operation() {
delete model.userNames[model.selecteduserName];
}// Button
}
]// content
}// FlowPanel
}// BorderPanel
visible: true
}// Frame
} catch(e:SQLException) {
e.printStackTrace();
}