大数据分析技术之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小项目
谢谢阅读。

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