大數據分析技術之JAVA基礎(七):IO和JDBC

寫在開頭:這個部分我們還是跟上上一節一樣會更多的使用到NetBeans的可視化操作,主要文章以JDBC爲主IO爲輔。

學習內容安排

JAVA基礎課程學習:數據類型(一)、運算符表達式和程序結構控制(二)、面向對象基礎:類與對象和接口(三)、面向對象基礎:繼承抽象多態封裝(四)、異常類和常用實用類(五)、組件和事件處理(六)、IO和JDBC(七)、泛型和集合函數(八)。

七、IO和JDBC

1.IO
首先來了解一下什麼是IO,其實就是輸入和輸出流,將數據進行輸入到java程序中或者將java程序中的數據進行輸出,在本節內容中不做重點展開講解,僅簡單介紹一下File類與隨機流,當然還有很多各種各樣的IO類,感興趣的讀者可自行閱讀《java 2 使用教程》相關內容。
1.1File類
File對象主要是獲取文件本身的一些信息對於文件的內容讀寫操作均不涉及,也即是可以獲得一些文件的長度之類的意思。有一些常見的方法見下圖
在這裏插入圖片描述
下面我們通過一個小例子來說明一下,首先需要在對應文件夾下創建一個文件,這裏我們創建一個mm.txt,然後讀取其文件名和長度,

package test7;

import java.io.File;

public class Test7 {
    public static void main(String[] args) {
       
        File ff = new File("src/test7/mm.txt"); //如果文件存在則找到,如果沒有則創建一個
        String name = ff.getName();
        System.out.println(name);
        System.out.println(ff.length());
    }  
}
run:
mm.txt
4742

1.2RandomAccessFile類
使用RandomAccessFile類來創建一個隨機訪問文件流,這與前面的File類不同,因爲這個隨機流可以對文件的內容進行更改,其常用的方法有以下幾個,
在這裏插入圖片描述
下面通過一個例子我們來展示一下這些方法的使用如何正確讀取出一個文件,同樣需要自己提前準備一個文件,助理我們需要自己throws一個報錯,當然也不是必須的,然後使用try來進行測試運行。對於隨機流讀取文件的方法是一行一行的進行readline,這裏使用while的循環控制,當光標還在文件內時就繼續readline文件直到讀取完畢。


package test7;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class Test7 {

    public static void main(String[] args) throws FileNotFoundException, IOException {
  
        RandomAccessFile ff = new RandomAccessFile("src/test7/mm.txt", "rw");//rw表示可以讀寫文件
        try{
            long x = ff.length();
            while(ff.getFilePointer() < x){
                String ss = ff.readLine();
                String sss = new String(ss.getBytes("iso-8859-1"));//將編碼轉爲iso-8859-1
                System.out.println(sss);
            }
        }catch (IOException ex){
            System.out.println("文件輸入有問題");
        }
    }  
}
run:
"The Delegation of Sichuan Tourism University Visited SWUFE\n"
                + "On May 31st, the delegation of Sichuan Tourism University, including YAN Qipeng, Secretary of the Party Committee, BAI Jie, Vice President, and representatives of related departments visited SWUFE. ZHAO Dewu, Chairman of the University Council, LI Yongqiang, Vice President as well as representatives of President's Office, Office of Organization and Personnel, Office of Academic Affairs, School of Accounting, School of Marxism, and School of Economic Information Engineering had a discussion in the meeting room 604 of Tengxiang Building.\n"
                + " ZHAO Dewu extended a sincere welcome to YAN's visit. He introduced the general situation, historical development, development status, strategic objectives and development ideas of SWUFE. ZHAO Dewu pointed out that with Chinese Socialism's entrance into a new era, financial and economic higher education has also entered the \"new financial and economic\" era. In this context, profound changes have taken place in the discipline, organizational members and university functions. Colleges and universities should actively adapt to the changes and enhance their subjective initiatives. He hopes that both sides will further strengthen exchanges and cooperation and jointly promote development in the future.\n"
                + "YAN Qipeng expressed thanks for SWUFE's warm reception. He introduced the development history and faculty of Sichuan Tourism University, hoping to further learn from SWUFE's good practices and experience in discipline construction and talent training and further establish a long-term mechanism to strengthen in-depth exchanges and cooperation.\n"
                + "At the meeting, both sides had in-depth exchanges on talent training, grass-roots party building and comprehensive management etc.\n"
                + "After the meeting, the delegation visited the History Museum of SWUFE and the Museum of Money and Finance. (Office of the University Council)\n"
                + "Senior Diplomat of Ministry of Foreign Affairs ZHANG Limin Delivered A Lecture in SWUFE\n"
                + "In the afternoon of On May 28th, ZHANG Limin, a senior diplomat and former ambassador of the Ministry of Foreign Affairs, gave a lecture on the theme of \"China's diplomacy and the International Situation\" in the Conference Room 101 of Hongyuan Building in SWUFE. OU Bing, Vice Chairman of the University Council presided over the lecture. Student representatives from the fifth training course for college student cadres as well as Head Start classrooms of talent training for international organizations presented the lecture.\n"
                + "Before the lecture, OU Bing gave a brief introduction ZHANG. On behalf of SWUFE, he expressed a warm welcome to ZHANG Limin. OU sincerely hoped that students would cherish the opportunity of face-to-face communication with ZHANG. SWUFE students are expected to understand the national conditions, have a global view and strive to become innovative talents who are familiar with international rules.\n"
                + "In the lecture, on the basis of his nearly four decades of diplomatic experience, ZHANG introduced some basic knowledge, diplomatic etiquette in the international diplomacy, the main tasks and work contents of embassies and consulates abroad. He further expounded the significance of diplomacy and the basic requirements of personal quality for a diplomat. He also combed the history of China's diplomatic development, the current international situations and China's foreign policy. He then shared his insights on recent hot topics. He stressed that students should pay attention to the changes in world economy as well as science and technology and to analyze problems by using professional knowledge. Meanwhile, he encouraged students to participate in international organizations' internship and employment to make China heard throughout the world.\n"
                + "In the Q&A session, ZHANG patiently responded to the questions from students. Students said that the lecture has greatly extended their horizon. They have been keenly aware of the patriotic feelings, and realized the glory of working as a diplomat for the country.\n"
                + "ZHANG Limin is a senior diplomat of the Ministry of Foreign Affairs, a former Ambassador of the Chinese Embassy in Italy, Consul General of the Consulate General in Milan, former Chinese Ambassador to Guyana, and now the member of the Council for Promoting South-South Cooperation as well as the special consultant to the Research Center for Latin America, SWUFE. (Student Affairs Department, School of International Business)";

2.JDBC
下面開始來介紹JDBC,也就是通過java來對數據庫進行操作,我們使用的軟件的版本如下,應該是NetBeans8.2支持MySQL5.1,然後Navicat for MySQL是對MySQL的一種可視化的操作系統,與SQL Server類似。

軟件名 版本號
NetBeans 8.2
MySQL 5.1
Navicat for MySQL 11.0.1

在有軟件的基礎上,我們會以一個小項目的角度來進行分享,項目最後的產品是一個可以登錄、註冊、權限管理等的一個窗口,同樣使用於上一節一樣的風格來展示如何去搭建這樣一個操作窗口,過於的一些常識性細節,將不再贅述。筆者默認爲讀者熟悉SQL、JAVA、NetBeans可視化操作,整個項目分爲如下幾個板塊,
1.數據的準備
2.窗口的搭建
3.登錄窗口的搭建
4.註冊窗口的搭建
5.權限管理窗口的搭建(待完成)
6.功能窗口的實現(待完成)
7.功能的添加以及退出按鈕的實現
下面開始吧!
2.1數據的準備
首先我們需要通過Navicat for MySQL創建表和數據,這個需要提前安裝配置好MySQL,然後點擊連接,並輸入想要取的連接名字,並輸入密碼,這裏筆者的用戶名和密碼都是root,輸入完成後就可以開始創建數據庫,在這裏插入圖片描述
右鍵剛剛新創立的鏈接,選擇新建數據庫,這裏的選擇如下圖所示,在這裏插入圖片描述
然後對新創建的數據庫中右鍵表,並選擇新建表,設置好每一列的內容和類型就可以了,然後保存。最後雙擊表提前先輸入幾個數據,方便後面測試,在這裏插入圖片描述
在這裏插入圖片描述
好了數據的創建就到這裏結束了,下面開始我們的窗口設計了,
2.2窗口的搭建
首先放一個我們搭建好的窗口的樣子,
在這裏插入圖片描述
首先創建一個JFrame的程序,進入一個NetBeans的可視化界面,先添加Swing容器中的拆分窗口分別右鍵兩個窗口,設置佈局爲邊框佈局,然後添加Swing控件中的樹,放在左邊,放一個文本區域在右邊。
下面需要改變左側的內容,點擊坐整個程序最左邊的導航器,然後點擊右鍵JjTree1,點擊屬性,選擇model,將裏面的內容進行更改爲我們想要的,一個空格表示分級。最後就形成了我們上面所展示的界面。在這裏插入圖片描述
窗口設計完了後還有一個重要的事情就是,設置點擊左側的內容會進行窗口的跳轉,這個內容需要在其他類都完成的情況下進行,下面我們先對裏面的功能進行完善吧。
2.3登錄窗口的搭建
我們需要再相同目錄下重新創建一個JPane的窗口,然後先將界面設置爲,如下形式,這個窗口的設計在上一篇文章中已經講過了可以自行查閱。
在這裏插入圖片描述
然後需要對submit按鈕進行完善,這裏就需要鏈接數據庫,思路大致是,當輸入的ID和Password與數據庫中相對應的時候就輸出,否則就報錯。那麼我們爲了方便,我們需要首先創立一個連接數據庫的類,來方便後面的調用,代碼如下。
這裏我們需要對工程添加JDBC庫,如圖右鍵添加庫,選擇JDBC即可在這裏插入圖片描述
然後來編寫類來實現數據庫的對接,在輸入數據庫連接時,爲了解決中文的問題,就需要在數據庫mydb後面加上如下代碼?useSSL=true&characterEncoding=gb2312

package tt;

import java.sql.Connection;
import java.sql.DriverManager;

public class DbCon {
   public static Connection dbCon(){
       Connection con = null;
       try {
           Class.forName("com.mysql.jdbc.Driver");//構建引擎   
           con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?useSSL=true&characterEncoding=gb2312", "root", "root");//連接數據庫     
       } catch (Exception e) {
       }
       return con; //返回Connection的值,方便後面SQL語句的輸入。
   } 
}

然後對submit按鈕時間進行完善,右鍵按鈕進行事件,創建Action事件,然後再對應的地方輸入代碼,如下,SQL語句這裏使用的是PreparedStatement,

try {
	Connection con = DbCon.dbCon(); //調用剛剛建立的Connection對象
	PreparedStatement ps = con.prepareStatement("select * from users where id = ? and password = ?");//使用sql語句進行查詢
	//對第一個問號,填充int值,值就是文本框輸入的
	Integer.parseInt(jTextField1.getText().trim())); 
	//對第二個問號,填充string值,值就是密碼框輸入的
	ps.setString(2, jPasswordField1.getText().trim());
	//將SQL語句進行傳輸
	ResultSet rs = ps.executeQuery();
	//使用next進行光標移動,將符合條件的進行消息框的輸出,
	if(rs.next()){
		String name = rs.getString(2);
		JOptionPane.showMessageDialog(this, "welcom "+name," ",JOptionPane.INFORMATION_MESSAGE);
}else{
		JOptionPane.showMessageDialog(this, "Wrong id or password", "", JOptionPane.ERROR_MESSAGE);
		}
	} catch (Exception e) {
}

注意這裏不能直接運行,需要在第一個窗口處運行,具體的代碼會在最後實現,現在展示一下功能,當正確輸入時,會顯示如下圖,錯誤的話就回報錯。然後Reset按鈕就是點擊後全部清空,這裏不做說明。
在這裏插入圖片描述
2.4註冊窗口的搭建

大體上思路和登錄窗口差不多,也需要重新創立一個JPane窗口,設計出來的窗口如下,
在這裏插入圖片描述
註冊成功的思路就是當輸入的兩次密碼相同的時候,這當然是最簡單的思路,於是就需要對Submit按鈕事件代碼進行編寫,這裏的id是自動生成的,所以我們需要使用last將光標調到最後一個讀取當前最後的id然後+1生成新的id,這裏使用的是insert插入的操作,需要對value裏面的5個問號(也就是所有的列)進行值的填充,就從上面輸入框裏輸入的內容進行填充。最後使用executeUpdate()更新數據,即可完成操作,

        String p1 = jPasswordField1.getText().trim();
        String p2 = jPasswordField2.getText().trim();
        if(p1.equals(p2)){
            try {
                Connection con = DbCon.dbCon();
                PreparedStatement ps = con.prepareStatement("select * from users");
                ResultSet rs = ps.executeQuery();
                rs.last();
                int newid = rs.getInt(1)+1;
                ps = con.prepareStatement("insert into users value(?,?,?,?,?)");
                ps.setInt(1, newid);
                ps.setString(2, jTextField1.getText().trim());
                ps.setString(3, p1);
                ps.setString(4, jTextField2.getText().trim());
                ps.setFloat(5, Integer.parseInt(jTextField3.getText().trim()));
                ps.executeUpdate();
                JOptionPane.showMessageDialog(this,"註冊成功, your id is "+newid, "", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
            }
        }else{    
		}

當我們註冊成功的時候會出現以下的彈窗,
在這裏插入圖片描述
由於其他功能還沒有完善,所以後期框架搭建好了後會繼續分享。從數據庫中可以看到數據被重成功插入,在這裏插入圖片描述

2.5權限管理窗口(待完成)
2.6功能窗口(待完成)
2.7功能的添加以及退出按鈕的實現
接下來我們需要將實現的登記和註冊的功能和初始窗口進行連接,整體邏輯是,首先需要點擊左側的按鈕,這個我們稱爲樹,首先需要對是否點擊樹進行判斷,然後判斷是點的哪一個按鈕。
實現過程如下,
首先右鍵導航器裏的jTree1,選擇定製代碼,然後再下面空白處加入監聽,
在這裏插入圖片描述
然後再源代碼的最上面添加樹的接口,代碼如下,
在這裏插入圖片描述
然後完成監聽接口,代碼如下,

public void valueChanged(TreeSelectionEvent e) {
    //將選擇某個功能的值轉爲node值
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)jTree1.getLastSelectedPathComponent();
    //然後提取選擇的node值是什麼
    String ss = node.getUserObject().toString();
    //通過if語句判斷是否爲樹上的節點,然後判斷是哪一個功能
    if(node.isLeaf() && ss.equals("Login")){
    	//創建功能類,這裏需要提前完善相關JPanle
        Login lo = new Login();
        //選擇將功能窗口輸出到分塊的右邊窗口
        jSplitPane1.setRightComponent(lo);
        //刷新一下
        this.validate();
    }else if(node.isLeaf() && ss.equals("Register")){
        System.out.println("register");
        Register rr = new Register();
        jSplitPane1.setRightComponent(rr);
        this.validate();
    }else if(node.isLeaf() && ss.equals("Quit")){
    	//該語句退出窗口
        System.exit(0);
    }
}

於是通過這幾個板塊的代碼就實現了這個項目的其中一部分,其他剩下的會在之後進行補充。


結語
好了今天的分享到此結束,我們手動完成了一個登錄和註冊的JDBC小項目
謝謝閱讀。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章