javafx学习之数据库操作
上次我们学习的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();
}

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.
