第15周作业

一、题目

编写一个应用程序,输入用户名和密码,访问test数据库中t_login表(字段包括id、username、password),验证登录是否成功。

二、源代码

package TwentuSixth;
/*
 * 通过JDBC直连和加载驱动建立连接,两个textfiled分别接受username和password通过sql语句查询并输出结果
 * 
 * 
 */
import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Test extends JFrame {

    private JPanel contentPane;
    private JTextField textField;
    private JTextField textField_1;
    Connection con = null;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Test frame = new Test();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        
        JLabel label = new JLabel("\u7528\u6237\u540D\uFF1A");
        label.setBounds(66, 72, 54, 15);
        contentPane.add(label);
        
        JLabel label_1 = new JLabel("\u5BC6\u7801\uFF1A");
        label_1.setBounds(66, 134, 54, 15);
        contentPane.add(label_1);
        
        textField = new JTextField();
        textField.setBounds(173, 69, 164, 21);
        contentPane.add(textField);
        textField.setColumns(10);
        
        textField_1 = new JTextField();
        textField_1.setBounds(173, 134, 164, 21);
        contentPane.add(textField_1);
        textField_1.setColumns(10);
        
        JButton button = new JButton("\u767B\u5F55");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                 try {
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","0000");
                     Statement st = con.createStatement();
                     ResultSet rs = st.executeQuery("select * from t_login where username = '"+textField.getText()+"' and password = '"+textField_1.getText()+"'");
                     if(rs.next()){
                            JOptionPane.showMessageDialog(null, "登陆成功!");
                        }else{
                            JOptionPane.showMessageDialog(null, "登陆失败。");
                        }
                        if(rs!=null){
                            rs.close();
                        }
                        st.close();
                        con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                
                
            }
        });
        button.setBounds(147, 200, 93, 23);
        contentPane.add(button);
    }
}

三、运行结果

第15周作业_第1张图片

 

 

一、题目

在上一题基础上,当登录成功后,将t_user表(id、name、sex、birthday)的信息进行显示(要求使用DB.java完成登录和获取t_user表中数据的操作),最后再对t_user表进行一条记录的添加操作。

二、源代码

1.DB.java

package TewntySeventh;
/*
 * DB类,存放加载驱动,直连方式和各种方法
 * 
 * 
 */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DB {
    private Connection con;
    private PreparedStatement pre;
    private ResultSet rs;
    private static DB db;

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    DB() {
        try {
            con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/test", "root", "0000");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static DB getInstance() {
        if (db == null) {
            db = new DB();
        }
        return db;
    }

    public ResultSet executeSelect(String sql, Object[] args) {
        try {
            pre = con.prepareStatement(sql);
            if (args.length != 0) {
                for (int i = 0; i < args.length; i++) {
                    pre.setObject(i + 1, args[i]);
                }
            }
            rs = pre.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    public int executeModify(String sql, Object[] args) {
        int n = 0;
        try {
            pre = con.prepareStatement(sql);
            if (args.length != 0) {
                for (int i = 0; i < args.length; i++) {
                    pre.setObject(i + 1, args[i]);
                }
            }
            n = pre.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return n;
    }

    public void close() {
        try {
            if (rs != null) {
                rs.close();
            }
            pre.close();
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

2.Login.java

package TewntySeventh;
/*
 * 和上面的一样,通过JDBC直连并判断结果然后输出
 * 
 * 
 */
import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Login extends JFrame {

    private JPanel contentPane;
    private JTextField textField;
    private JTextField textField_1;
    Connection con = null;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Login frame = new Login();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Login() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        
        JLabel label = new JLabel("\u7528\u6237\u540D\uFF1A");
        label.setBounds(66, 72, 54, 15);
        contentPane.add(label);
        
        JLabel label_1 = new JLabel("\u5BC6\u7801\uFF1A");
        label_1.setBounds(66, 134, 54, 15);
        contentPane.add(label_1);
        
        textField = new JTextField();
        textField.setBounds(173, 69, 164, 21);
        contentPane.add(textField);
        textField.setColumns(10);
        
        textField_1 = new JTextField();
        textField_1.setBounds(173, 134, 164, 21);
        contentPane.add(textField_1);
        textField_1.setColumns(10);
        
        JButton button = new JButton("\u767B\u5F55");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                 try {
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","0000");
                     Statement st = con.createStatement();
                     ResultSet rs = st.executeQuery("select * from t_login where username = '"+textField.getText()+"' and password = '"+textField_1.getText()+"'");
                     if(rs.next()){
                            JOptionPane.showMessageDialog(null, "登陆成功!");
                            Select Select=new Select();
                            Select.setVisible(true);
                            setVisible(false);
                        }else{
                            JOptionPane.showMessageDialog(null, "登陆失败。");
                        }
                        if(rs!=null){
                            rs.close();
                        }
                        st.close();
                        con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                
                
            }
        });
        button.setBounds(147, 200, 93, 23);
        contentPane.add(button);
    }
}

3.Select.java

package TewntySeventh;
/*
 * 加载DB里面的executeSelect方法获取查询结果,然后通过Jtable将其显示
 * 
 */
import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;
import javax.swing.border.LineBorder;
import java.awt.Color;
import javax.swing.border.TitledBorder;
import javax.swing.UIManager;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.ResultSet;

public class Select extends JFrame {

    private JPanel contentPane;
    private JTable table;
    private String str[]={"id","name","sex","birthday"};
    private JButton button_1;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Select frame = new Select();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Select() {
        setTitle("\u5217\u8868\u663E\u793A\u5143\u7D20");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 500);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(10, 20, 414, 387);
        contentPane.add(scrollPane);
        

        table = new JTable();
        table.setModel(new DefaultTableModel(
            new Object[][] {
                {null,null,null,null},
            },
            new String[] {
                "id", "name", "sex", "birthday"
            }
        ));
        scrollPane.setViewportView(table);
        
        JButton button = new JButton("\u67E5\u8BE2");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                DB db=new DB();
                ResultSet s=db.executeSelect("select * from t_user",new Object[]{});
                try {
                    if(s.last()){
                        int a=s.getRow();
                        Object[][] date=new Object[a][];
                        int b=s.getMetaData().getColumnCount();
                        s.beforeFirst();
                        int i=0;
                        while (s.next()) {
                            date[i]=new Object[b];
                            for (int j = 0; j < b; j++) {
                                date[i][j]=s.getObject(j+1);
                            }
                            i++;
                        }
                        DefaultTableModel m=new DefaultTableModel(date,str);
                        table.setModel(m);
                    }
                    
                } catch (Exception e) {
                    // TODO: handle exception
                }
                table.setVisible(false);
                table.setVisible(true);
            }
        });
        button.setBounds(82, 417, 93, 23);
        contentPane.add(button);
        
        button_1 = new JButton("\u6DFB\u52A0");
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                Add add=new Add();
                add.setVisible(true);
                setVisible(false);
                /*Select Select=new Select();
                Select.setVisible(true);
                setVisible(false);*/
            }
        });
        button_1.setBounds(257, 417, 93, 23);
        contentPane.add(button_1);

        /*
        JFrame frame = new JFrame();
        String[] columnNames = { "火影", "风影", "雷影", "水影", "土影" };
        DefaultTableModel model = new DefaultTableModel(columnNames, 0);
        JTable jTable = new JTable(model);
        JScrollPane scrollPane = new JScrollPane(jTable);
        frame.add(scrollPane);
        frame.pack();
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
        // 获取JTable中的model
        DefaultTableModel model2 = (DefaultTableModel) jTable.getModel();
        String[] column1 = { "初代火影", "初代风影", "初代雷影", "初代水影", "初代土影" };
        model.addRow(column1);
        
        */

    }
}

4.Add.java

package TewntySeventh;
/*
 * 获取testfiled的值将其做返回,radiobutton放进group里,然后根据不同的返回值获取相应的值并输出
 * 
 * 
 */
import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.ResultSet;

public class Add extends JFrame {

    private JPanel contentPane;
    private final ButtonGroup buttonGroup = new ButtonGroup();
    private JTextField textField;
    private JTextField textField_1;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Add frame = new Add();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Add() {
        setTitle("\u6DFB\u52A0\u4FE1\u606F");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        
        JLabel label = new JLabel("\u7528\u6237\u540D\uFF1A");
        label.setBounds(46, 51, 66, 15);
        contentPane.add(label);
        
        JLabel label_1 = new JLabel("\u51FA\u751F\u65E5\u671F\uFF1A");
        label_1.setBounds(46, 167, 66, 15);
        contentPane.add(label_1);
        
        JRadioButton rdbtnNewRadioButton = new JRadioButton("\u7537");
        rdbtnNewRadioButton.setActionCommand("1");
        buttonGroup.add(rdbtnNewRadioButton);
        rdbtnNewRadioButton.setBounds(132, 109, 45, 23);
        contentPane.add(rdbtnNewRadioButton);
        
        JRadioButton rdbtnNewRadioButton_1 = new JRadioButton("\u5973");
        rdbtnNewRadioButton_1.setActionCommand("0");
        buttonGroup.add(rdbtnNewRadioButton_1);
        rdbtnNewRadioButton_1.setBounds(196, 109, 51, 23);
        contentPane.add(rdbtnNewRadioButton_1);
        
        textField = new JTextField();
        textField.setBounds(132, 48, 143, 21);
        contentPane.add(textField);
        textField.setColumns(10);
        
        textField_1 = new JTextField();
        textField_1.setBounds(132, 164, 143, 21);
        contentPane.add(textField_1);
        textField_1.setColumns(10);
        
        JButton button = new JButton("\u63D0\u4EA4");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                DB db=new DB();
                String buttonGroupText=buttonGroup.getSelection().getActionCommand();
                int s=db.executeModify("insert into t_user (name,sex,birthday)values('"+textField.getText()+"','"+buttonGroupText+"','"+textField_1.getText()+"')", new Object[]{});
                if(s>0){
                    JOptionPane.showMessageDialog(null, "添加成功!");
                }else{
                    System.out.print("添加失败\n");
                }
            }
        });
        button.setBounds(84, 211, 93, 23);
        contentPane.add(button);
        
        JLabel label_2 = new JLabel("\u6027\u522B\uFF1A");
        label_2.setBounds(46, 113, 45, 15);
        contentPane.add(label_2);
        
        JButton btnNewButton = new JButton("\u8FD4\u56DE\u67E5\u770B\u5217\u8868");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                Select Select=new Select();
                Select.setVisible(true);
                setVisible(false);
            }
        });
        btnNewButton.setBounds(230, 211, 126, 23);
        contentPane.add(btnNewButton);
    }
}

三、运行结果

第15周作业_第2张图片

 

你可能感兴趣的:(第15周作业)