JAVA与MySQL连接并显示、管理表格实例

Main类:主要负责UI显示。

  1 package ConnectToMysql;
  2 
  3 import java.awt.event.*;
  4 import javax.swing.*;
  5 import javax.swing.table.*;
  6 
  7 import java.awt.*;
  8 import java.util.*;
  9 
 10 public class Main extends JFrame{
 11     static JPanel MainPanel,ButtonPanel;
 12     static JLabel Pages;
 13     static JButton Insert,Select,PageUp,PageDown,Page1,PageN;
 14     static DBConnect DBC;
 15     static PageController PC = new PageController();
 16     static JTable Table;
 17     static String ob[][] = new String[20][4];
 18     static Font EnFont = new Font("Times New Roman",Font.BOLD,20);
 19     static Font CnFont = new Font("宋体",Font.BOLD,20);
 20     public Main() {
 21         this.setTitle("Test");
 22         DBC = new DBConnect();
 23         ButtonPanel = new JPanel(null);
 24         ButtonPanel.setPreferredSize(new Dimension(800,100));
 25         this.add(ButtonPanel,BorderLayout.SOUTH);
 26         Select = new JButton("Select");
 27         Select.setBounds(180,55,150,40);
 28         Select.setFont(EnFont);
 29         Select.setEnabled(true);
 30         Select.setMargin(new Insets(0,0,0,0));
 31         Select.addActionListener(new ActionListener() {
 32             public void actionPerformed(ActionEvent e) {
 33                 PC = new PageController(DBC.SelectAll());
 34                 Show(PC.ShowThisPage(1));
 35                 Pages.setText(ResetText(1,PC.PageNum));
 36             }
 37         });
 38         ButtonPanel.add(Select);
 39         Insert = new JButton("Insert");
 40         Insert.setBounds(450,55,150,40);
 41         Insert.setFont(EnFont);
 42         Insert.setEnabled(true);
 43         Insert.setMargin(new Insets(0,0,0,0));
 44         Insert.addActionListener(new ActionListener() {
 45             public void actionPerformed(ActionEvent e) {
 46                 Object[] options = { "I know" }; //please wait
 47                 JOptionPane.showOptionDialog(null, "Information is being randomly generated into the database. This process may last for tens of seconds. Please wait for the prompt box to pop up.", "Attention Please", 
 48                 JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, 
 49                 null, options, options[0]); 
 50                 DBC.RandomInsert();
 51                 JOptionPane.showOptionDialog(null, "The data is generated successfully and you can use it normally.", "Success", 
 52                 JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, 
 53                 null, options, options[0]); 
 54             }
 55         });
 56         ButtonPanel.add(Insert);
 57         MainPanel = new JPanel();
 58         this.add(MainPanel);
 59         Table = new JTable();
 60         this.add(Table);
 61         
 62         PageUp = new JButton("<");
 63         PageUp.setBounds(200,10,80,30);
 64         PageUp.setFont(EnFont);
 65         PageUp.addActionListener(new ActionListener() {
 66             public void actionPerformed(ActionEvent e) {
 67                 Vector V = PC.previousPage();
 68                 Show(V);
 69                 Pages.setText(ResetText(PC.PageIndex,PC.PageNum));
 70             }
 71         });
 72         ButtonPanel.add(PageUp);
 73         
 74         PageDown = new JButton(">");
 75         PageDown.setBounds(500,10,80,30);
 76         PageDown.setFont(EnFont);
 77         PageDown.addActionListener(new ActionListener() {
 78             public void actionPerformed(ActionEvent e) {
 79                 Vector V = PC.nextPage();
 80                 Show(V);
 81                 Pages.setText(ResetText(PC.PageIndex,PC.PageNum));
 82             }
 83         });
 84         ButtonPanel.add(PageDown);
 85         
 86         Page1 = new JButton("<<");
 87         Page1.setBounds(100,10,80,30);
 88         Page1.setFont(EnFont);
 89         Page1.addActionListener(new ActionListener() {
 90             public void actionPerformed(ActionEvent e) {
 91                 Vector V = PC.ShowThisPage(1);
 92                 Show(V);
 93                 Pages.setText(ResetText(PC.PageIndex,PC.PageNum));
 94             }
 95         });
 96         ButtonPanel.add(Page1);
 97         
 98         PageN = new JButton(">>");
 99         PageN.setBounds(600,10,80,30);
100         PageN.setFont(EnFont);
101         PageN.addActionListener(new ActionListener() {
102             public void actionPerformed(ActionEvent e) {
103                 Vector V = PC.ShowThisPage(PC.PageNum);
104                 Show(V);
105                 Pages.setText(ResetText(PC.PageIndex,PC.PageNum));
106             }
107         });
108         ButtonPanel.add(PageN);
109         
110         Pages = new JLabel("Page :  Total :",JLabel.CENTER);
111         Pages.setBounds(300,10,180,30);
112         Pages.setFont(EnFont);
113         ButtonPanel.add(Pages);
114         
115         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
116         this.setSize(800, 800);
117         Dimension winSize = Toolkit.getDefaultToolkit().getScreenSize();   
118         this.setLocation((winSize.width - this.getWidth()) / 2,(winSize.height - this.getHeight()) / 2);
119         this.setResizable(false);
120         this.setVisible(true);
121     }
122     
123     public String ResetText(int x,int tot) {
124         String ans = "Page : ";
125         ans += String.valueOf(x);
126         ans += " , Total : ";
127         ans += String.valueOf(tot);
128         return ans;
129     }
130     
131     public void Show(Vector V) {
132         ob = new String[20][4];
133         int L = V.size();
134         for(int i = 0;i < L;i ++) {
135             String sp[] = String.valueOf(V.get(i)).split(" ");
136             ob[i][0] = sp[0];
137             ob[i][1] = sp[1];
138             ob[i][2] = sp[2];
139             ob[i][3] = sp[3];
140         }
141         Table.getTableHeader().setFont(EnFont);
142         Table.setFont(EnFont);
143         Table.setRowHeight(30);
144         Table.setModel(new DefaultTableModel(ob,new String[] { "ID", "Name", "Sex", "Tel"}));
145         this.getContentPane().add(Table.getTableHeader(),BorderLayout.NORTH);
146         this.getContentPane().add(Table, BorderLayout.CENTER);
147     }
148     
149     public static void main(String[] args) {
150         new Main();
151     }
152 }

DBConnect类:负责向MySql建立连接并格式化Sql语句,本实例有清空表,向表插入数据以及选择表中全部数据三个功能。

使用的驱动为JDBC,用户名为user,密码为123456。

  1 import java.sql.*;
  2 import java.util.*;
  3 
  4 public class DBConnect {
  5          private String driver;
  6         private String url;
  7         private String user;
  8         private String password;
  9         static Random Rand = new Random();
 10         DBConnect () {
 11             //DataBase name : db_test
 12             //Table name : personal_information
 13             //you need to build a database and a table first
 14             Random Rand = new Random();
 15             driver = "com.mysql.cj.jdbc.Driver";
 16             url = "jdbc:mysql://localhost:3306/db_test?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";
 17             user = "root";
 18             password = "123456";
 19         }
 20         
 21         public int RandNum(int x) {
 22             return Rand.nextInt(x);
 23         }
 24         public String RandSex() {
 25             int sex = Rand.nextInt(10);
 26             if(sex % 2 == 1) {
 27                 return "Male";
 28             }
 29             return "Female";
 30         }
 31         public String RandName() {
 32             int L = RandNum(5) + 5;
 33             String name = "";
 34             for(int i = 0;i < L;i ++) {
 35                 name += (char)((RandNum(100) % 26) + 'a');
 36             }
 37             return name;
 38         }
 39         public String RandTel() {
 40             String tel = "";
 41             for(int i = 0;i < 9;i ++) {
 42                 if(i == 3) {tel += "-";}
 43                 tel += String.valueOf(RandNum(100) % 10);
 44             }
 45             return tel;
 46         }
 47         
 48         void RandomInsert(){
 49             Connection conn;
 50             PreparedStatement stmt;
 51             try {// delete all information
 52                 Class.forName(driver);
 53                 conn = DriverManager.getConnection(url, user, password);
 54                 String SQL = "delete from personal_information";
 55                 stmt = (PreparedStatement) conn.prepareStatement(SQL);
 56                 stmt.execute();
 57             } catch (ClassNotFoundException e) {e.printStackTrace();}
 58             catch (SQLException e) {e.printStackTrace();}
 59             
 60             int cnt = 200 + RandNum(20);
 61             for(int i = 0;i < cnt;i ++) {// insert random information
 62                 try {
 63                     Class.forName(driver);
 64                     conn = DriverManager.getConnection(url, user, password);
 65                     String SQL = "insert into personal_information values (?,?,?,?)";
 66                     stmt = (PreparedStatement) conn.prepareStatement(SQL);
 67                     stmt.setString(1, String.valueOf(i + 100000));
 68                     stmt.setString(2, RandName());
 69                     stmt.setString(3, RandSex());
 70                     stmt.setString(4, RandTel());
 71                     stmt.executeUpdate();
 72                     stmt.close();     
 73                     conn.close(); 
 74                 } catch (ClassNotFoundException e) {}
 75                 catch (SQLException e) {}
 76             }
 77         }
 78         
 79         Vector SelectAll() {//select all information
 80             Vector rowData = new Vector();
 81             try {
 82                 Class.forName(driver); 
 83                 Connection conn = DriverManager.getConnection(url, user, password); 
 84                 Statement state = conn.createStatement(); 
 85                 String SQL = "select db_test.personal_information.ID,"
 86                         + "db_test.personal_information.Name,"
 87                         + "db_test.personal_information.Sex,"
 88                         + "db_test.personal_information.Tel "
 89                         + "from db_test.personal_information";
 90                 ResultSet rst = state.executeQuery(SQL); 
 91                 while (rst.next()) {
 92                     String P = "";
 93                     P += rst.getString("ID") + " ";
 94                     P += rst.getString("Name") + " ";
 95                     P += rst.getString("Sex") + " ";
 96                     P += rst.getString("Tel");
 97                     rowData.add(P);
 98                 }
 99                 rst.close();
100                 state.close();
101                 conn.close();
102             } catch (Exception e) {}
103             return rowData;
104         }
105         
106 }

PageController类:负责管里表格中的数据,每个函数直接操作成员变量,再使用类中方法Select(),对当前页码中应有的数据依次存放并传出至调用的地方。

 1 import java.sql.*;
 2 import java.util.*;
 3 
 4 public class PageController {
 5     static Vector AllList = new Vector();
 6     static Vector NowList=new Vector();
 7     static int PageIndex = 1;//now page        
 8     static int PageSize = 20;//every page
 9     static int PageNum; //total page
10     static int L;//total information
11     
12     public PageController(){}
13     
14     public PageController(Vector V){
15         this.PageIndex = 1;
16         this.AllList = V;
17         this.L = V.size();
18         this.PageNum = (L + PageSize - 1) / PageSize;
19     }
20     
21     public Vector ShowThisPage(int x) {   
22         this.PageIndex = x;
23         return select();
24     }
25 
26     
27     public Vector nextPage() {
28         if (PageIndex < PageNum) {
29              PageIndex ++;
30         } 
31         return select();  
32     }
33     
34     public Vector previousPage() {
35         if (PageIndex > 1) {
36               PageIndex --;
37         }
38        return select();
39     }
40 
41     public Vector select(){
42         NowList = new Vector();
43         for(int i = (PageIndex-1)*PageSize; i < PageIndex*PageSize && i < L; i++){
44                NowList.add(AllList.get(i));
45         }
46         return NowList;
47     }
48     
49 }

 运行情况图示:

原文地址:https://www.cnblogs.com/love-fromAtoZ/p/11587141.html