首頁 資料庫 mysql教程 javafx学习之数据库操作

javafx学习之数据库操作

Jun 07, 2016 pm 03:36 PM
java 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();
}
 

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

突破或從Java 8流返回? 突破或從Java 8流返回? Feb 07, 2025 pm 12:09 PM

Java 8引入了Stream API,提供了一種強大且表達力豐富的處理數據集合的方式。然而,使用Stream時,一個常見問題是:如何從forEach操作中中斷或返回? 傳統循環允許提前中斷或返回,但Stream的forEach方法並不直接支持這種方式。本文將解釋原因,並探討在Stream處理系統中實現提前終止的替代方法。 延伸閱讀: Java Stream API改進 理解Stream forEach forEach方法是一個終端操作,它對Stream中的每個元素執行一個操作。它的設計意圖是處

mysql:簡單的概念,用於輕鬆學習 mysql:簡單的概念,用於輕鬆學習 Apr 10, 2025 am 09:29 AM

MySQL是一個開源的關係型數據庫管理系統。 1)創建數據庫和表:使用CREATEDATABASE和CREATETABLE命令。 2)基本操作:INSERT、UPDATE、DELETE和SELECT。 3)高級操作:JOIN、子查詢和事務處理。 4)調試技巧:檢查語法、數據類型和權限。 5)優化建議:使用索引、避免SELECT*和使用事務。

PHP:網絡開發的關鍵語言 PHP:網絡開發的關鍵語言 Apr 13, 2025 am 12:08 AM

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

PHP與Python:了解差異 PHP與Python:了解差異 Apr 11, 2025 am 12:15 AM

PHP和Python各有優勢,選擇應基於項目需求。 1.PHP適合web開發,語法簡單,執行效率高。 2.Python適用於數據科學和機器學習,語法簡潔,庫豐富。

Java程序查找膠囊的體積 Java程序查找膠囊的體積 Feb 07, 2025 am 11:37 AM

膠囊是一種三維幾何圖形,由一個圓柱體和兩端各一個半球體組成。膠囊的體積可以通過將圓柱體的體積和兩端半球體的體積相加來計算。本教程將討論如何使用不同的方法在Java中計算給定膠囊的體積。 膠囊體積公式 膠囊體積的公式如下: 膠囊體積 = 圓柱體體積 兩個半球體體積 其中, r: 半球體的半徑。 h: 圓柱體的高度(不包括半球體)。 例子 1 輸入 半徑 = 5 單位 高度 = 10 單位 輸出 體積 = 1570.8 立方單位 解釋 使用公式計算體積: 體積 = π × r2 × h (4

PHP與其他語言:比較 PHP與其他語言:比較 Apr 13, 2025 am 12:19 AM

PHP適合web開發,特別是在快速開發和處理動態內容方面表現出色,但不擅長數據科學和企業級應用。與Python相比,PHP在web開發中更具優勢,但在數據科學領域不如Python;與Java相比,PHP在企業級應用中表現較差,但在web開發中更靈活;與JavaScript相比,PHP在後端開發中更簡潔,但在前端開發中不如JavaScript。

MySQL:世界上最受歡迎的數據庫的簡介 MySQL:世界上最受歡迎的數據庫的簡介 Apr 12, 2025 am 12:18 AM

MySQL是一種開源的關係型數據庫管理系統,主要用於快速、可靠地存儲和檢索數據。其工作原理包括客戶端請求、查詢解析、執行查詢和返回結果。使用示例包括創建表、插入和查詢數據,以及高級功能如JOIN操作。常見錯誤涉及SQL語法、數據類型和權限問題,優化建議包括使用索引、優化查詢和分錶分區。

PHP與Python:核心功能 PHP與Python:核心功能 Apr 13, 2025 am 12:16 AM

PHP和Python各有優勢,適合不同場景。 1.PHP適用於web開發,提供內置web服務器和豐富函數庫。 2.Python適合數據科學和機器學習,語法簡潔且有強大標準庫。選擇時應根據項目需求決定。

See all articles