Java(Gui)连接Sql Server 登录案例

GUI连接Sql Server数据库实现用户

注意:这个连接需要一个jar包,下载之后需要导入到自己的java项目加载,用于java连接数据库

地址:链接:https://pan.baidu.com/s/1yCxfo0iNvMa1P0xPqhakDg 提取码:1111

步骤1(数据库操作)

--创建数据库
create database jdbcmmsql
use jdbcmmsql
--创建表
create table user_t
(
	id int not null primary key,
	name varchar(20) not null,
	pwd varchar(32) not null,
	sex char(2),
	age int
)
--插入数据
insert into user_t
values
(1,'123','123456','女',22)

步骤2(java操作)

2.1构建java与Sql server的连接

package Gui.db;
import java.sql.Connection;
import java.sql.DriverManager;
public class DbHelper {
    Connection conn = null;
    public DbHelper() {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            //这里要根据自己的 库名,账号,密码连接。
            conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=jdbcmmsql", "sa", "123456Mssql");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public Connection getConn() {
        return conn;
    }
}

2.2创建实体类

package Gui.entity;

public class User {
    private int id;
    private String name;
    private String pwd;
    private String sex;
    private int age;
    public User() {
    }
    public User(int id, String name, String pwd, String sex, int age) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
        this.sex = sex;
        this.age = age;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

2.3接口层(dao)

package Gui.dao;
import Gui.entity.User;
import java.util.List;
public interface UserDao {
    //增
    public boolean addEmp(User emp);
    //删
    public int delEmp(int id);
    //改
    public int updEmp(User emp);
    //单查
    public User findone(String user,String pwd);
    //查
    public List<User> findAll();
}

接口实现类

只实现了一部分

package Gui.dao;

import Gui.db.DbHelper;
import Gui.entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao{
    Connection conn;
    PreparedStatement ps;
    ResultSet rs;
    //增加
    public boolean addEmp(User user) {
        boolean flag = false;
        conn = new DbHelper().getConn();
        String sql = "insert into user_t(id,name,pwd,sex,age) values(?,?,?,?,?)";
        try {
            ps = conn.prepareStatement(sql);
            ps.setInt(1, user.getId());
            ps.setString(2, user.getName());
            ps.setString(3, user.getSex());
            ps.setInt(4, user.getAge());
            ps.setInt(5, user.getAge());
            if(ps.executeUpdate()>0) {
                flag = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }
    //删除
    public int delEmp(int id) {
        return 0;
    }
    //修改
    public int updEmp(User emp) {
        return 0;
    }
    //单查,可用于登录
    public User findone(String usera, String userpwd) {
        User user_t = null;
        conn = new DbHelper().getConn();
        String sql = "select name,pwd from user_t";
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()){
                user_t = new User();
                user_t.setName(rs.getString("name"));
                user_t.setPwd(rs.getString("pwd"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user_t;
    }
    //全查
    public List<User> findAll() {
        List<User> ul = new ArrayList<User>();
        User user = null;
        conn = new DbHelper().getConn();
        String sql = "select * from user_t";
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setName(rs.getString("name"));
                user.setPwd(rs.getString("pwd"));
                user.setSex(rs.getString("sex"));
                user.setAge(rs.getInt("age"));
                ul.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ul;
    }
}

2.4登录跳转的新窗口

package Gui.Login;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
	登录成功打开此窗口,有一个案例小游戏
*/
public class LoginYes {
    public LoginYes(){
        JFrame f = new JFrame("你登陆成功了,来玩个小游戏吧😀");
        f.setLayout(new FlowLayout());
        f.setBounds(300,400,500,200);
        //创建Lable标签对象
        JButton j1 = new JButton("请输入0-4的数字");
        //创建输入框
        TextField tf = new TextField(40);
        f.add(tf);
        f.add(j1);
        tf.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e1) {
                j1.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e2) {
                        char ch = e1.getKeyChar();
                        switch (ch){
                            case '0':
                                j1.setText("zero");
                                break;
                            case '1':
                                j1.setText("one");
                                break;
                            case '2':
                                j1.setText("two");
                                break;
                            case '3':
                                j1.setText("three");
                                break;
                            case '4':
                                j1.setText("four");
                                break;
                        }
                    }
                });
            }
        });
        f.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        f.setVisible(true);
    }
}

2.5运行类

package Gui;

import Gui.Login.LoginNo;
import Gui.Login.LoginYes;
import Gui.dao.UserDaoImpl;
import Gui.entity.User;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Test {
    public static void main(String[] args) {
        //创建JFrame实例
        JFrame jf = new JFrame("登陆界面");
        //设置框架的宽度和高度
        jf.setSize(350,200);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //创建面板,类似于HTML的div标签
        JPanel panel = new JPanel();
        //添加面板
        jf.add(panel);
        //调用用户定义的方法并添加组件到面板
        placeComponents(panel);
        //设置界面可见
        jf.setVisible(true);
    }

    private static void placeComponents(JPanel panel){
        panel.setLayout(null);
        //创建JLabel
        JLabel userlabel = new JLabel("账号:");
        userlabel.setBounds(10,20,80,25);
        panel.add(userlabel);
        //创建文本域用于用户输入
        JTextField userText = new JTextField(20);
        userText.setBounds(100,20,165,25);
        panel.add(userText);
        //输入密码的文本域
        JLabel passwordLabel = new JLabel("密码:");
        passwordLabel.setBounds(10,50,80,25);
        panel.add(passwordLabel);
        //密码框--未用真正密码框实现
        JTextField passwordText = new JTextField(20);
        passwordText.setBounds(100,50,165,25);
        panel.add(passwordText);
        //创建登录按钮
        JButton loginButton = new JButton("登录");
        loginButton.setBounds(10,80,80,25);
        panel.add(loginButton);

        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String user_str= userText.getText();
                String user_pwd = passwordText.getText();
                System.out.println(user_str);
                System.out.println(user_pwd);
                UserDaoImpl ud = new UserDaoImpl();
                User u = ud.findone(user_str,user_pwd);
                if(u.getName().equals(user_str) && u.getPwd().equals(user_pwd)){
                    new LoginYes();
                }else {
                    //登录失败这里会弹出来一个报错的小对话框
                    JOptionPane.showMessageDialog(null, "请检查账号和密码", "登录失败", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
    }
}
posted @ 2021-12-12 18:39  刘盛哲的学习笔记  阅读(620)  评论(0编辑  收藏  举报