上次我们学习的javafx连接数据库的简单操作,这次我们来做一个稍为复杂的操作数据库示例.IDE是:netbeans 6 beat 2,数据库用javaDB(jdb6自带有javaDB数据库,netbeans 6也带有,本例使用IDE自带的javaDB),由于水平问题中文只注解了部份代码,请见谅.(如出错,请把
上次我们学习的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();
}

使用Java13中的新的JavaFXWebView组件来显示网页内容随着Java的不断发展,JavaFX已经成为构建跨平台图形界面的主要工具之一。JavaFX提供了丰富的图形库和组件,让开发者能够轻松地创建各种各样的用户界面。其中,JavaFXWebView组件是一个非常有用的组件,它允许我们在JavaFX应用程序中显示网页内容。在Java13中,J

JavaFX是Java平台的一个用户界面框架,类似于Swing,但却更加现代化和灵活。然而在使用时可能会遇到一些视图错误,本文将介绍如何处理和避免这些错误。一、JavaFX视图错误的类型在使用JavaFX时,可能会遇到以下几种视图错误:NullPointerException这是最常见的错误之一,通常在尝试访问未初始化或不存在的对象时发生。这可能

如何在Java9中使用JavaFX来构建响应式UI界面引言:在计算机应用程序的开发过程中,用户界面(UI)是非常重要的一部分。一个好的UI能够提升用户体验,使应用程序更具吸引力。JavaFX是Java平台上的一个图形用户界面(GUI)框架,它提供了一套丰富的工具和API来快速构建富有交互性的UI界面。在Java9中,JavaFX已经成为了JavaSE的

JavaFX是一个用于构建富客户端应用程序的框架,但是在使用过程中,可能会遇到一些JavaFX图形错误,这会影响应用程序的正常运行。本文将介绍如何处理和避免JavaFX图形错误。一、JavaFX图形错误的种类JavaFX图形错误有多种类型,包括以下几个方面:1.线程错误:JavaFX需要在UI线程上执行,如果在后台线程上执行JavaFX代码,就会引发线程错误

如何在Java9中使用JavaFX和WebSocket实现实时通信的图形界面引言:随着互联网的发展,实时通信的需求越来越普遍。在Java9中,我们可以使用JavaFX和WebSocket技术来实现具有图形界面的实时通信应用。本文将介绍如何在Java9中使用JavaFX和WebSocket技术来实现实时通信的图形界面,并附上相应的代码示例。第一部分:Ja

随着技术的不断发展,我们现在可以使用不同的技术来构建桌面应用程序。而SpringBoot和JavaFX则是现在较为流行的选择之一。本文将重点介绍如何使用这两个框架来构建一个功能丰富的桌面应用程序。一、介绍SpringBoot和JavaFXSpringBoot是一个基于Spring框架的快速开发框架。它可以帮助开发者快速构建Web应用程序,同时提供一组开

使用Java13中的新的JavaFX模块来开发图形界面应用程序随着Java13的发布,新的JavaFX模块也被引入,使得开发图形界面应用程序变得更加简便和灵活。本文将介绍如何使用JavaFX模块来开发一个简单的图形界面应用程序,并提供一些代码示例。在开始之前,请确保您已经安装了Java13JDK,并已正确配置了相关的环境变量。首先,在Java13中

在进行JavaFX应用程序开发的过程中,我们常常会遇到JavaFX线程卡顿错误。这种错误的严重程度不同,可能会对程序的稳定性和性能产生不利的影响。为了保证程序的正常运行,我们需要了解JavaFX线程卡顿错误的原因和解决方法,以及如何预防这种错误的发生。一、JavaFX线程卡顿错误的原因JavaFX是一个多线程的UI应用程序框架,它允许程序在后台线程中执行长时


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
