Java作业二:身份证号分析系统 (含MySQL数据库连接)

本人一直想找时间系统整理一下之前做过的一些实验,便于后续用到的时候可以尽快的使用,po出来也便于大家交流学习,有问题欢迎交流指正,与诸君共勉!

要求

了解身份证编码的规则,然后从键盘输入10个身份证号码,判断号码是否有问题,如果为有效的身份证号码则给出对应的信息。然后用异常情况处理最后一位为非数字的情况,给出提示。判断输入的身份证蕴含信息(出生地、性别、年龄等信息)。最好含可视化界面。

代码

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
import java.util.Vector;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

/** 
 * @author AGATHA
 * @date 2022年10月5日
 * @todo 该类为身份证号码查验系统主类
 * 含系统数据库增删查改功能、系统首页控制台版和GUI版的驱动
 */
public class IdNumberCheckSys{
	
	/**
	 * 显示系统内身份证号六位地区码对应地区数据库 (便于系统更新)
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 */
	public static void showIdNumAddrSQL() throws SQLException, ClassNotFoundException {
		//1.加载驱动
		Class.forName("com.mysql.cj.jdbc.Driver");
		//2.用户信息和url
		String url = "jdbc:mysql://localhost:3306/idnumbercity?useUnicode=true&characterEncoding=utf8&useSSL=true";
		String username="root";
		String password="123456";
		//3.连接成功,数据库对象 Connection
		Connection connection = DriverManager.getConnection(url,username,password);
		//4.执行SQL对象Statement,执行SQL的对象
		Statement statement = connection.createStatement();
		//5.执行SQL的对象去执行SQL,返回同省份地址编码结果集 
		String sql = "SELECT * FROM IdNum_Addr";
		ResultSet resultSet = statement.executeQuery(sql);
		while (resultSet.next()) {
			System.out.print(resultSet.getInt("id")+"\t");
			System.out.print(resultSet.getString("zone")+"\t");
			System.out.print(resultSet.getString("desc")+"\t");
			System.out.println();
		}
		resultSet.close();
		connection.close();
		statement.close();
	}
	
	/**
	 * 删除系统数据库主键为id的数据
	 * @throws ClassNotFoundException 
	 * @throws SQLException 
	 * 
	 */
	public static void deleteIdNumAddrSQL(int id) throws ClassNotFoundException, SQLException {
		//UPDATE tablename SET gender = '男' WHERE id = 4
		Class.forName("com.mysql.cj.jdbc.Driver");
	    //2.用户信息和url
		String url = "jdbc:mysql://localhost:3306/idnumbercity?useUnicode=true&characterEncoding=utf8&useSSL=true";
		String username="root";
		String password="123456";
		//3.连接成功,数据库对象 Connection
		Connection connection = DriverManager.getConnection(url,username,password);
		//4.执行SQL对象Statement,执行SQL的对象
		Statement statement = connection.createStatement();
		PreparedStatement pstm = null;
		//5.执行SQL的对象去执行SQL,返回同省份地址编码结果集 
		String sql_delete = "DELETE FROM IdNum_Addr WHERE id =" + id;
		pstm = connection.prepareStatement(sql_delete);
		int row = pstm.executeUpdate();
		System.out.println("删除数据成功"+row+"行受到影响");
		pstm.executeUpdate();
	    statement.close();
	    connection.close();
	    pstm.close();
	}
	
	/**
	 * 向系统数据库添加地区码及描述数据
	 * @param addr
	 * @param desc
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 */
	public static void addToIdNumAddrSQL(String addr,String desc) throws SQLException, ClassNotFoundException {
		String province = addr.substring(0, 2);
		String city = addr.substring(0, 4);
		String zone = addr.substring(0, 6);
		Class.forName("com.mysql.cj.jdbc.Driver");
	    //2.用户信息和url
		String url = "jdbc:mysql://localhost:3306/idnumbercity?useUnicode=true&characterEncoding=utf8&useSSL=true";
		String username="root";
		String password="123456";
		//3.连接成功,数据库对象 Connection
		Connection connection = DriverManager.getConnection(url,username,password);
		//4.执行SQL对象Statement,执行SQL的对象
		Statement statement = connection.createStatement();
		PreparedStatement pstm = null;
		//5.执行SQL的对象去执行SQL,返回同省份地址编码结果集 
		//String sql_add = "INSERT INTO IdNum_Addr VALUES(null," + province+","+ city + "," + zone +","+desc+")";
		
		String sql_add = "INSERT INTO IdNum_Addr VALUES(null,"+province+","+city+","+zone+",'"+desc+"');";
		
		pstm = connection.prepareStatement(sql_add);
		pstm.executeUpdate();	
	    statement.close();
	    connection.close();
	    pstm.close();
		System.out.println("添加数据成功!");
	}
	
	/**
	 * 修改系统库中某条地址码对应信息
	 * @param id
	 * @param addr
	 * @param desc
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public static void alterIdNumAddrSQL(int id,String addr) throws ClassNotFoundException, SQLException {
		String province = addr.substring(0, 2);
		String city = addr.substring(0, 4);
		String zone = addr.substring(0, 6);
		Class.forName("com.mysql.cj.jdbc.Driver");
	    //2.用户信息和url
		String url = "jdbc:mysql://localhost:3306/idnumbercity?useUnicode=true&characterEncoding=utf8&useSSL=true";
		String username="root";
		String password="123456";
		//3.连接成功,数据库对象 Connection
		Connection connection = DriverManager.getConnection(url,username,password);
		//4.执行SQL对象Statement,执行SQL的对象
		Statement statement = connection.createStatement();
		String sql0 = "SELECT * FROM IdNum_Addr where id = "+ id;
      ResultSet resultSet = statement.executeQuery(sql0);
      
      if(resultSet == null) {
      	System.out.println("数据库中不存在id为"+id+"的数据,请查验数据库后再输入id");
      	return;
      }
	String sql_alter1 = "UPDATE IdNum_Addr SET province = "+province+" where id="+id;
      PreparedStatement pst1 = connection.prepareStatement(sql_alter1);
      pst1.executeUpdate();
      String sql_alter2 = "UPDATE IdNum_Addr SET city = "+city+" where id="+id;
      PreparedStatement pst2 = connection.prepareStatement(sql_alter2);
      pst2.executeUpdate();
      String sql_alter3 = "UPDATE IdNum_Addr SET zone = "+zone+" where id="+id;
      PreparedStatement pst3 = connection.prepareStatement(sql_alter3);
      pst3.executeUpdate();
	  statement.close();
	  connection.close();
	  resultSet.close();
	  pst1.close();
	  pst2.close();
	  pst3.close();
	  System.out.println("修改数据成功!");
	}
	
	/**
	 * 系统地区码变更(根据中华人民共和国行政区划代码)增删查改
	 * @throws Exception 
	 */
	public static void changeIdNumAddrSQL() throws Exception {
		Scanner reader = new Scanner(System.in);
		System.out.println("请选择要对系统库执行的变更操作: (1)删除地区码数据  (2)添加地区码数据  (3)修改地区码数据");
		System.out.print("请选择您的操作(输入1-3数字):");
		int choice1 = reader.nextInt();
		switch(choice1) {
		case 1://删除
			System.out.print("请输入您要删除地区码数据的id:");
			int c1 = reader.nextInt();
			deleteIdNumAddrSQL(c1);
			break;
		case 2://添加
			System.out.print("请输入您要添加的六位地区码:");
		    String ad1 = reader.next();
		    if(ad1.length() != 6) {
				throw new Exception("输入地区码格式错误");
			}
		    System.out.print("请输入您要添加的地区描述:");
		    String desc1 = reader.next();
		    addToIdNumAddrSQL(ad1, desc1);
		    break;
		case 3://修改
			System.out.print("请输入您要修改地区码数据的id:");
			int c2 = reader.nextInt();
			System.out.print("请输入您要改为的地区码:");
			String ad2 = reader.next();
			if(ad2.length() != 6) {
			    throw new Exception("输入地区码格式错误");
			}
			alterIdNumAddrSQL(c2, ad2);//含数据合法性查验
			break;
		}
	}
	
	/**
	 * 系统输入身份证号进行身份信息查询
	 */
	public static void inPutIdNumber() {
		Scanner reader = new Scanner(System.in);
  	System.out.println("您要查询几个身份证号码信息?");
  	int n1 = reader.nextInt();
  	String[] idNums = new String[n1];
  	for(int i = 1;i <= n1;i++) {
  		System.out.print("请输入第"+(i)+"条身份证号:");
          idNums[i-1] = reader.next();
          try {
				IdNumberVertification.IsValidateIdNumber(idNums[i-1]);//进行合法性检验
			} catch (Exception e) {
				e.printStackTrace();
				return;
			}
  	}
  	System.out.println("查询结果如下:----------------------");
  	for(int i = 0; i < n1;i++) {
  		try {
  		System.out.println(IdNumberInformation.showIdNumberInfo(idNums[i]));//展示身份信息
  		} catch (Exception e) {
  			e.printStackTrace();
  		}
  	} 	
	}
	
	/**获取系统当前时间*/
	public static String getcurrentTime() {
		Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
		String time = dateFormat.format(date);
		return time;
	}
	
	/**控制台版系统首页*/
	public static void HomePageMenu() {
		System.out.println("==========欢=迎=使=用=身=份=证=信=息=查=验=系=统==========");
		System.out.println("| "+getcurrentTime()+"                           |");
		System.out.println("|----------------请选择您的操作----------------------|");
		System.out.println("|         ①身份证号查询身份信息(含合法性检验)");
		System.out.println("|         ②查看身份证地区码对应地区数据");
		System.out.println("|         ③变更系统地区码数据库");
		System.out.println("|         ④退出系统");
		System.out.println("|================================================|");
	}	
	
	/**
	 * 系统主函数 含操作台版和GUI版的驱动
	 * @param args
	 */
	public static void main(String[] args){
	 // IdCheckFrame idf = new IdCheckFrame("身份证号查验系统");
	  Scanner reader = new Scanner(System.in);
      boolean fig = true;
      while(fig) {
      	HomePageMenu();
  		int choice = reader.nextInt();
  		int choice0 = 0;
			//防止输入不规范bug
			if(choice == 1)choice0 = 1;
			else if(choice == 2)choice0 = 2;
			else if(choice == 3)choice0 = 3;
			else if(choice == 4)choice0 = 4;
			else System.out.println("请输入1~4的数字!");
      	switch (choice0){
  		case 1:
		       inPutIdNumber();
		       break;//接收输入信息并查验
  		case 2:
  			System.out.println("可能需要等待......");
				try {
					showIdNumAddrSQL();
				} catch (ClassNotFoundException | SQLException e) {
					e.printStackTrace();
				}break;
  		case 3:
  			try {
					changeIdNumAddrSQL();
				} catch (Exception e) {
					e.printStackTrace();
				}break;
  		case 4://系统退出
				System.out.println("系统已退出!");return;
			default:
				break;
          }
      	reader.nextLine();//吸收回车符
			System.out.println("按回车键返回主界面");
			reader.nextLine();
	    }  
      reader.close();
   }	
}

/** 
 * @author AGATHA
 * @date 2022年10月4日
 * @TODO 该类用于根据18位身份证号获取和输出个人的信息
 */
class IdNumberInformation{
	 /**
	  * 二代身份证于2004年开始换发,至2013年后,中国居民身份证均为18位的二代身份证
	  * 香港、澳门、台湾的居民居住证也统一为18位
	  */
	 private static final int CHINA_ID_LENGTH = 18;
		
	 /** 根据身份证号获取户籍省份二位编码(1、2位)*/
	 public static String getProvince(String IdNumber) {
         String sProvinNum = "";
         if (IdNumber.length() == CHINA_ID_LENGTH) {
             sProvinNum = IdNumber.substring(0, 2);
         }
         return sProvinNum;
     }
	 
     /** 根据身份证号前六位与数据库比对 返回户籍地址具体信息*/
	public static String resAddr(String IdNumber) throws ClassNotFoundException, SQLException{
		if (IdNumber.length() != CHINA_ID_LENGTH) {
			return null;
		}
		//1.加载驱动
	    Class.forName("com.mysql.cj.jdbc.Driver");
	    //2.用户信息和url
	    String url = "jdbc:mysql://localhost:3306/idnumbercity?useUnicode=true&characterEncoding=utf8&useSSL=true";
	    String username="root";
	    String password="123456";
	    //3.连接成功,数据库对象 Connection
	    Connection connection = DriverManager.getConnection(url,username,password);
	    //4.执行SQL对象Statement,执行SQL的对象
	    Statement statement = connection.createStatement(); 
	    //5.执行SQL的对象去执行SQL,返回同省份地址编码结果集 
	    String sql = "SELECT * FROM IdNum_Addr where province = "+getProvince(IdNumber);
	    ResultSet resultSet = statement.executeQuery(sql);
	    String describe = "";
        while (resultSet.next()) {
            String zone = resultSet.getString("zone");//得到该省某地区编码
            //若地区编码相同(前六位)
        	if(zone.equals(IdNumber.substring(0, 6))){
        	    describe = resultSet.getString("desc");
        	}
        } 
        resultSet.close();
        statement.close();
	    connection.close();
        return describe;//返回地址信息    
	}
	/**根据18位身份证号获取出生年份*/
	public static String getBirthYear(String IdNumber) {
		if (IdNumber.length() != CHINA_ID_LENGTH) {
			return null;
		}
		String BirthYear = IdNumber.substring(6, 10);
		return BirthYear;
	}
	/**根据18位身份证号获取出生月份*/
	public static String getBirthMonth(String IdNumber) {
		if (IdNumber.length() != CHINA_ID_LENGTH) {
			return null;
		}
		String BirthMonth = IdNumber.substring(10, 12);
		return BirthMonth;
	}
	/**根据18位身份证号获取出生日*/
	public static String getBirthDay(String IdNumber) {
		if (IdNumber.length() != CHINA_ID_LENGTH) {
			return null;
		}
		String BirthDay = IdNumber.substring(12, 14);
		return BirthDay;
	}
	
	/** 根据身份证号返回出生年月日信息 */
	public static String resBirthday(String IdNumber) {
		if (IdNumber.length() != CHINA_ID_LENGTH) {
			return null;
		}
		String res = getBirthYear(IdNumber)+"年"+ getBirthMonth(IdNumber)+"月"+getBirthDay(IdNumber)+"日";
		return res;
	}
	
	/**根据身份证号返回性别信息*/
	public static String getGender(String IdNumber){
		if (IdNumber.length() != CHINA_ID_LENGTH) {
			return null;
		}
		String gender = "unknown";
		String GenderNum = IdNumber.substring(16, 17);		
		if (Integer.parseInt(GenderNum) % 2 != 0) {
			gender = "男";
		}else if (Integer.parseInt(GenderNum) % 2 == 0)
		gender = "女";
		return gender;
	}

	/**
	 * 输出身份证号及其信息
	 * @param IdNumber 18位身份证号
	 */
	public static String showIdNumberInfo(String IdNumber) {
		String s = "";
		try {
			s = "身份证号:"+IdNumber+"\n户籍地址:"+resAddr(IdNumber)+"   出生日期:"+resBirthday(IdNumber)+"   性别:"+getGender(IdNumber);
			return s;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return s;
	}
}


/**
 * @author AGATHA
 * @date 2022年10月4日
 * @TODO 该类用于18位身份证号的合法性检验
 */
class IdNumberVertification {
	private static final int CHINA_ID_LENGTH = 18;
	
	 /**验证字符串中各位是否均为数字 */
	public static boolean isNum(String val) {
		return val == null || "".equals(val) ? false : val.matches("^[0-9]*$");
	}
	
	/**每位都是数字的字符串转化为整型数组 */
	public static int[] converStringToInt(String val) {
		if(isNum(val)==false)
			return null;
		else {
			int len = val.length();
			int[] ii = new int[len];
			for(int i = 0; i < len;i++) {
				ii[i] = Integer.parseInt(val.substring(i,i+1));
			}
			return ii;
		}
	}
	
	/**根据身份证号前17位计算校验码与第18位比较是否合法 */
	public static boolean calCheckCode(String IdNumber) {
		if (IdNumber.length() != CHINA_ID_LENGTH) {
			return false;
		}
		final int[] weightingFac = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
		final char[] CHECK_number = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
		char[] idnum = IdNumber.toCharArray();
		String IdNumber_17 = IdNumber.substring(0, 17);
		int[] number_17 = new int[17];
		int mulsum = 0;
		number_17 = converStringToInt(IdNumber_17);
		for(int i = 0; i < 17;i++) {
			//相乘加
			mulsum += number_17[i] * weightingFac[i];
		}
		int cn = mulsum%11;
		boolean flag = (idnum[17] == CHECK_number[cn]);
		return flag;
	}
	
	/**
	 * 检验某身份证日期是否合法 
	 * @param year 四位年份  出生日期-年
	 * @param month 两位月份 出生日期-月
	 * @param day 两位日期  出生日期-日    
	 * @return
	 */
	public static boolean isDate(String year,String month,String day) {
		int y = Integer.parseInt(year);
		int m = Integer.parseInt(month);
		int d = Integer.parseInt(day);
		Calendar date = Calendar.getInstance();
	    String m_YEAR = String.valueOf(date.get(Calendar.YEAR));
	    final int MAX_YEAR = Integer.parseInt(m_YEAR);//当前年份(最大年份)
	    final int MIN_YEAR = MAX_YEAR - 150;//定义最小年份
	    if(y > MAX_YEAR || y < MIN_YEAR) {//年
	    	return false;
	    }
	    if(m > 12 || m == 0) {//月
	    	return false;
	    }
	    //天数基本要求
	    boolean flag1 = (d > 31)||(d == 0);
	    //2月天数 考虑是否为闰年
	    boolean flag2 = isLeapYear(year) && m == 2 && d > 29;
	    boolean flag3 = !isLeapYear(year) && m == 2 && d > 28;
	    //4、6、9、12月只有30天
	    boolean flag4 = (m == 4 || m == 6 || m == 9 || m == 12) && d == 31;
	    if(flag1 || flag2 || flag3 || flag4) {//日
	    	return false;
	    }
	    return true;
	}
	
	/**
	 * 判断某年份是否为闰年
	 * @param year  四位年份
	 * @return
	 */
	public static boolean isLeapYear(String year) {
		boolean flag = false;
		int y = Integer.parseInt(year);
		//年份被4整除 且 不被100整除  或  年份被400整除 为闰年
		if(y % 4 == 0 && y % 100 != 0) {
			flag = true;
		}else if(y % 400 == 0) {
			flag = true;
		}
		return flag;
	}
	
	/**判断身份证号六位地区码是否合法 */
	public static boolean isValiAddrNum(String AddrNum) throws ClassNotFoundException, SQLException {
		//1.加载驱动
		Class.forName("com.mysql.cj.jdbc.Driver");
		//2.用户信息和url
        String url = "jdbc:mysql://localhost:3306/idnumbercity?useUnicode=true&characterEncoding=utf8&useSSL=true";
        String username="root";
        String password="123456";
        //3.连接成功,数据库对象 Connection
		Connection connection = DriverManager.getConnection(url,username,password);
        //4.执行SQL对象Statement,执行SQL的对象
        Statement statement = connection.createStatement();
        //5.执行SQL的对象去执行SQL,返回同省份地址编码结果集 
        String sql = "SELECT * FROM IdNum_Addr where zone = "+ AddrNum;
        ResultSet resultSet = statement.executeQuery(sql);
        statement.close();
	    connection.close();
        if(resultSet == null) {
        	return false;
        }
        resultSet.close();
        return true;
	}
		
	/**
	 * 判断身份证号最后一位是否非数字且非X,并在是的情况下抛出异常提示
	 * @param IdNumber
	 * @return
	 */
	public static boolean isValiNumCn(String IdNumber)throws Exception{
		boolean flag = isNum(IdNumber.substring(17,18))||IdNumber.substring(17,18).equals("X");
		if(flag == false) {
			throw new Exception("身份证号最末位非法!");
		}
		return flag; 
	}
	
	/**
	 * 验证18位身份证号码是否合法
	 * @param IdNumber 18位身份证号码
	 * @throws Exception
	 */
	public static void IsValidateIdNumber(String IdNumber) throws Exception{
		//验证身份证号码位数
		if (IdNumber.length() != CHINA_ID_LENGTH) {
			throw new Exception("身份证号码长度应为18位!");
		}
		//验证身份证号前六位地址码是否合法
		if(isValiAddrNum(IdNumber.substring(0,6)) == false){
			throw new Exception("身份证号码格式错误!");
		}
		//验证出生日期是否合法
		if(isDate(IdNumber.substring(6,10),IdNumber.substring(10,12),IdNumber.substring(12,14)) == false) {
			throw new Exception("身份证号码格式错误!");
		}
		//验证身份证号第18位校验码是否合法
		if(calCheckCode(IdNumber) == false) {
			throw new Exception("身份证号码无效!");
		}
		System.out.println("身份证号合法!");
	}
}


/**
 * @author AGATHA
 * @date 2022年10月6日
 * @todo 该类用于身份证查验系统的首页GUI设计
 */
class IdCheckFrame extends JFrame{
	private JPanel contentPane;
	private JLabel lab1, lab2, lab3, lab4, lab5,lab6,lab7,lab8;
	private JTextField tf1,tf2;
	private JTextArea text,ta,time;
	private JButton bt1; 
	private JMenuBar menubar;
	private JMenu menu1,menu2;
	
	/**首页 构造函数*/
	IdCheckFrame(String s){
		super(s);
		setSize(700,700);
		setLocationRelativeTo(null);
		contentPane = new JPanel();
		setContentPane(contentPane);
    	setBackground(Color.gray);
    	lab1 = new JLabel(new ImageIcon("src/身份.png"));
    	lab2 = new JLabel(new ImageIcon("src/身份认证.png"));
    	lab2.setSize(100,100);
    	lab2.setSize(100, 100);
    	time = new JTextArea(); 
    	Font f = new Font("宋体", Font.BOLD,10);
		time.setFont(f);
		time.append("系统时间:"+IdNumberCheckSys.getcurrentTime()); 
		time.setForeground(Color.black);
		time.setPreferredSize(new Dimension (200,10));
    	text = new JTextArea();  
		Font f0 = new Font("宋体", Font.BOLD,40);
		text.setFont(f0);
		text.append("欢迎使用 身份证号查验系统\n"); 
		text.setForeground(Color.black);
		text.setBackground(Color.white);
		text.setPreferredSize(new Dimension (550,50));
    	lab3 = new JLabel("身份证号:");
    	tf1 = new JTextField(30);
    	tf1.setPreferredSize(new Dimension (500,45));
    	lab4 = new JLabel("查询结果:");
    	ta = new JTextArea(10,22);
    	ta.setLineWrap(true); //激活自动换行功能 
    	ta.setWrapStyleWord(true);// 激活断行不断字功能
    	ta.setPreferredSize(new Dimension (200,200));
    	bt1 =new JButton("查询");	
    	menu1=new JMenu("首页");
		menu2=new JMenu("行政区划代码");
		menubar=new JMenuBar();
    	JPanel jp1 = new JPanel();
	    jp1.setLayout(new FlowLayout());
	    jp1.add(lab3);
	    jp1.add(tf1);
	    jp1.add(bt1);
	    JPanel jp2 = new JPanel();
	    jp2.setLayout(new FlowLayout());
	    jp2.add(lab2);
	    jp2.add(lab4);
	    jp2.add(ta);
	    contentPane.add(lab1);
    	contentPane.add(text);
    	contentPane.add(jp1);
    	contentPane.add(jp2);
    	menubar.add(menu1);
        menubar.add(menu2);     
        contentPane.add(time);
        this.setJMenuBar(menubar);
    	this.setVisible(true);
    	this.setResizable(false);
    	this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	
    	//“查询”按钮的点击事件
    	bt1.addActionListener(new ActionListener(){
           public void actionPerformed(ActionEvent e) {
               ta.setText(((JButton)e.getSource()).getText());
               try {
				IdNumberVertification.IsValidateIdNumber(tf1.getText());
			} catch (Exception e1) {
				e1.printStackTrace();
			}
               ta.setText(IdNumberInformation.showIdNumberInfo(tf1.getText()));
           }
       });
    	
    	//“行政区划代码”响应事件
    	menu2.addMenuListener(new MenuListener(){
    		  public void menuSelected(MenuEvent e) {
    			 sqlFrm();
               }
               public void menuDeselected(MenuEvent e) { }
               public void menuCanceled(MenuEvent e) { }
        });
	}
	
	/**获取数据库数据容器*/
	public static Vector sql() throws SQLException, ClassNotFoundException {
		Vector rows = null;
		Vector columnHeads = null;
		//1.加载驱动
		Class.forName("com.mysql.cj.jdbc.Driver");
		//2.用户信息和url
		String url = "jdbc:mysql://localhost:3306/idnumbercity?useUnicode=true&characterEncoding=utf8&useSSL=true";
		String username="root";
		String password="123456";
		//3.连接成功,数据库对象 Connection
		Connection connection = DriverManager.getConnection(url,username,password);
		//4.执行SQL对象Statement,执行SQL的对象
		Statement statement = connection.createStatement();
		//5.执行SQL的对象去执行SQL,返回同省份地址编码结果集 
		String sql = "SELECT * FROM IdNum_Addr";
		ResultSet resultSet = statement.executeQuery(sql);
		rows = new Vector();
		ResultSetMetaData rsmd = resultSet.getMetaData();
		while(resultSet.next()){
			rows.addElement(getNextRow(resultSet,rsmd));
		}
		resultSet.close();
        statement.close();
	    connection.close();
		return rows;
	}
	
	/**获取数据库表列名*/
	public static Vector getHead() throws ClassNotFoundException, SQLException{
		//Vector rows = null;
		Vector columnHeads = null;
		columnHeads = new Vector();
		//1.加载驱动
		Class.forName("com.mysql.cj.jdbc.Driver");
		//2.用户信息和url
		String url = "jdbc:mysql://localhost:3306/idnumbercity?useUnicode=true&characterEncoding=utf8&useSSL=true";
		String username="root";
		String password="123456";
		//3.连接成功,数据库对象 Connection
		Connection connection = DriverManager.getConnection(url,username,password);
		//4.执行SQL对象Statement,执行SQL的对象
		Statement statement = connection.createStatement();
		String sql = "SELECT * FROM IdNum_Addr";
		ResultSet resultSet = statement.executeQuery(sql);
		ResultSetMetaData rsmd = resultSet.getMetaData();
		for(int i = 1; i <= rsmd.getColumnCount(); i++)
			columnHeads.addElement(rsmd.getColumnName(i));
		resultSet.close();
		statement.close();
		connection.close();
		return columnHeads;
	}
	
	/**显示系统内所有行政地区码库GUI*/
	public static void sqlFrm() {
		JFrame sqlframe = new JFrame();
		sqlframe.setName("行政区划代码(系统数据)");
		DefaultTableModel tableModel;		// 默认显示的表格
		JButton add,del,alter;		
		JTable table;		// 表格
		sqlframe.setBounds(300, 200, 600, 450);		
		sqlframe.setLayout(new BorderLayout());	
		sqlframe.setLocationRelativeTo(null);
		
		JPanel ctPane = new JPanel();//按钮组件面板
		add = new JButton("增加");
		del = new JButton("删除");
		alter = new JButton("修改");
		ctPane.setLayout(new FlowLayout(FlowLayout.LEFT));
		ctPane.add(add);
		ctPane.add(del);
		ctPane.add(alter);
		try {//表列名称
			Vector rowData = sql();
			Vector columnNames = getHead();
			tableModel = new DefaultTableModel(rowData,columnNames);
			table = new JTable(tableModel);
			JScrollPane s = new JScrollPane(table);
			// 将面板和表格分别添加到窗体中
			sqlframe.add(ctPane,BorderLayout.NORTH);
			sqlframe.add(s);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		sqlframe.setVisible(true);	
		sqlframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		//“添加”按钮的点击事件
    	add.addActionListener(new ActionListener(){
           public void actionPerformed(ActionEvent e) {
        	//addToIdNumAddrSQL(addr,desc);//需要触发另一个frame
		   }
        });	
    	//“删除”按钮的点击事件
    	del.addActionListener(new ActionListener(){
           public void actionPerformed(ActionEvent e) {
        	//deleteIdNumAddrSQL(id);//需要触发另一个frame
		   }
        });	
    	//“修改”按钮的点击事件
    	alter.addActionListener(new ActionListener(){
           public void actionPerformed(ActionEvent e) {
        	//alterIdNumAddrSQL(id,addr);//需要触发另一个frame
		   }
        });	 
	}
	/**获取数据库表下一行数据*/
	private static Vector getNextRow(ResultSet rs, ResultSetMetaData rsmd)throws SQLException {
		Vector currentRow = new Vector(); // 定义一个向量,用于存放记录
		for (int i = 1; i <= rsmd.getColumnCount(); ++i)
		    currentRow.addElement(rs.getString(i)); // 获取记录
		return currentRow; // 返回记录
	}
}

系统运行结果:

点击“行政区划代码“可查看系统行政区划代码数据库:

操作台版系统首页:

对照身份证前6位,整理了6457条数据.形成了省市区县3级地区表 如下案例. INSERT INTO `area` VALUES ('1', '0', '1', '11', '1100', '110000', '北京市'); INSERT INTO `area` VALUES ('2', '1', '2', '11', '1101', '110100', '市辖区'); INSERT INTO `area` VALUES ('3', '2', '3', '11', '1101', '110101', '东城区'); INSERT INTO `area` VALUES ('4', '2', '3', '11', '1101', '110102', '西城区'); INSERT INTO `area` VALUES ('5', '2', '3', '11', '1101', '110103', '崇文区'); INSERT INTO `area` VALUES ('6', '2', '3', '11', '1101', '110104', '宣武区'); INSERT INTO `area` VALUES ('7', '2', '3', '11', '1101', '110105', '朝阳区'); INSERT INTO `area` VALUES ('8', '2', '3', '11', '1101', '110106', '丰台区'); INSERT INTO `area` VALUES ('9', '2', '3', '11', '1101', '110107', '石景山区'); INSERT INTO `area` VALUES ('10', '2', '3', '11', '1101', '110108', '海淀区'); INSERT INTO `area` VALUES ('11', '2', '3', '11', '1101', '110109', '门头沟区'); INSERT INTO `area` VALUES ('12', '2', '3', '11', '1101', '110110', '燕山区'); INSERT INTO `area` VALUES ('13', '2', '3', '11', '1101', '110111', '房山区'); INSERT INTO `area` VALUES ('14', '2', '3', '11', '1101', '110112', '通州区'); INSERT INTO `area` VALUES ('15', '2', '3', '11', '1101', '110113', '顺义区'); INSERT INTO `area` VALUES ('16', '2', '3', '11', '1101', '110114', '昌平区'); INSERT INTO `area` VALUES ('17', '2', '3', '11', '1101', '110115', '大兴区'); INSERT INTO `area` VALUES ('18', '2', '3', '11', '1101', '110116', '怀柔区'); INSERT INTO `area` VALUES ('19', '2', '3', '11', '1101', '110117', '平谷区');
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值