JAVA学习笔记(五十一)- DBUtil 封装数据库工具类

数据库工具类

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/*
 * 数据库工具类
 */
public class DBUtil {

    // 获取数据库连接
    public static Connection getConnection() {
        String driverClassName = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/test";
        String user = "root";
        String password = "123456";
        Connection conn = null;
        try {
            Class.forName(driverClassName);
            conn = DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    // 关闭所有
    public static void closeAll(ResultSet rs, Statement stmt, Connection conn) {
        try {
            if (rs != null)
                rs.close();
            if (stmt != null)
                stmt.close();
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            rs = null;
            stmt = null;
            conn = null;
        }
    }
}

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.JTextField;
import javax.swing.JLabel;
import java.awt.FlowLayout;
import javax.swing.JButton;

public class Login extends JFrame {

    private JPanel contentPane;
    private JTextField textField;

    /**
     * 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));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.CENTER);
        panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

        JLabel label = new JLabel("用户名");
        panel.add(label);

        textField = new JTextField();
        panel.add(textField);
        textField.setColumns(20);

        JButton btnNewButton = new JButton("登陆");
        panel.add(btnNewButton);
    }

}

查询相关信息

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class Test04 {
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    // 根据编号查询用户信息
    public User getUserById(int id) {
        User user = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/test", "root", "123456");
            /*
             * stmt = conn.createStatement(); String sql =
             * "select * from user where id=" + id;
             */
            String sql = "select * from user where id=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                user = new User(rs.getInt("id"), rs.getString("name"),
                        rs.getString("password"), rs.getInt("age"),
                        rs.getDate("birthday"));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                pstmt.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                rs = null;
                pstmt = null;
                conn = null;
            }
        }
        return user;
    }

    // 检查用户登陆,即判断用户名或密码是否正确
    public boolean checkLogin(User user) {
        boolean flag = false;
        /*String sql = "select *  from user where name=‘" + user.getName()
                + "‘ and password=‘" + user.getPassword() + "‘";*/
        String sql="select * from user where name=? and password=?";

        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/test", "root", "123456");
            pstmt=conn.prepareStatement(sql);
            pstmt.setString(1, user.getName());
            pstmt.setString(2, user.getPassword());
            rs=pstmt.executeQuery();
            if(rs.next()){
                flag=true;
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            try {
                rs.close();
                pstmt.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

    //查询所有用户信息
    public List<User> getAllUser(){
        List<User> users=new ArrayList<User>();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/test", "root", "123456");
            String sql = "select * from user";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while(rs.next()) {
                users.add(new User(rs.getInt("id"), rs.getString("name"),
                        rs.getString("password"), rs.getInt("age"),
                        rs.getDate("birthday")));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                pstmt.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                rs = null;
                pstmt = null;
                conn = null;
            }
        }
        return users;
    }

    //用户注册,即添加用户
    public void addUser(User user){
        String sql="insert into user values (null,?,?,?,?)";

        //调用工具类,获取连接Connection
        conn=DBUtil.getConnection();
        try {
            pstmt=conn.prepareStatement(sql);
            pstmt.setString(1, user.getName());
            pstmt.setString(2,user.getPassword());
            pstmt.setInt(3, user.getAge());
            pstmt.setDate(4, new Date(user.getBirthday().getTime()));//将java.util.Date转换为java.sql.Date
            pstmt.executeUpdate();
            System.out.println("添加用户成功!");
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            DBUtil.closeAll(rs, pstmt, conn);
        }
    }

    //根据编号删除用户信息
    public void deleteUserById(int id){

    }

    //更新用户信息
    public void updateUser(User user){

    }

    //根据编号范围和姓名模糊查询
    public List<User> getUserByCondition(int sid,int eid,String name){

        return null;
    }

    public static void main(String[] args) {
        Test04 test = new Test04();
        User user = test.getUserById(2);
        System.out.println(user);

        User user=new User("赵超","222222");
        boolean flag=test.checkLogin(user);
        System.out.println("是否登陆成功?"+flag);

        List<User> users=test.getAllUser();
        System.out.println(users);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date birthday=null;
        try {
            birthday = sdf.parse("2014-2-14");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        test.addUser(new User("余书石", "123456", 18, birthday));
    }
}

用户类,实体类

import java.util.Date;

/*
 * 用户类,实体类
 */
public class User {
    private int id;
    private String name;
    private String password;
    private int age;
    private Date birthday;

    public User(int id, String name, String password, int age, Date birthday) {
        super();
        this.id = id;
        this.name = name;
        this.password = password;
        this.age = age;
        this.birthday = birthday;
    }

    public User() {
    }

    public User(String name, String password, int age, Date birthday) {
        super();
        this.name = name;
        this.password = password;
        this.age = age;
        this.birthday = birthday;
    }

    public User(String name, String password) {
        super();
        this.name = name;
        this.password = password;
    }

    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 getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String toString() {
        return "User[id=" + id + ",name=" + name + ",age=" + age + ",birthday="
                + birthday + "]";
    }

}

创建数据库语句

create table user
(
    id int primary key auto_increment,
    name varchar(20) not null,
    password varchar(20),
    age int,
    birthday date
);
时间: 2024-08-02 23:05:16

JAVA学习笔记(五十一)- DBUtil 封装数据库工具类的相关文章

【JDBC编程】Java 连接 MySQL 基本过程以及封装数据库工具类

鉴于linux系统下安装oracle数据库过于麻烦,而相关的java连接mysql基本方法的参考文章过少且参差不齐,故本人查阅了一些书和网络资料写下此文章. 从数据库环境搭建.基本语法到封装工具类全过程,可作为参考.转载请注明来源. 一. 常用的JDBC API 1. DriverManager类 : 数据库管理类,用于管理一组JDBC驱动程序的基本服务.应用程序和数据库之间可以通过此类建立连接.常用的静态方法如下 static connection getConnection(String u

非专业码农 JAVA学习笔记 3 抽象、封装和类(2)

(2).静态域-放在内存公共存储单元,不放在特定的对象,用static修饰 (续上一篇<非专业码农 JAVA学习笔记 3 抽象.封装和类(1)>...) (3).静态初始器-由static引导的一对大括号括起来的语句组,作用跟构造函数相似 (4).最终域-final引导的,值在整个过程都不发生改变的 5.方法 (1)方法的定义:修饰词1 修饰词2…返回值类型 方法名(参数) throw[异常列表] 这里个人经验就是注意定义了返回值的方法,要在方法体里面增加return 该类型变量:此外遇到if

《Javascript权威指南》学习笔记之十一:处理字符串---String类和正则表达式

一.正则表达式的基本语法 1.概念:正则表达式由普通字符和特殊字符(元字符)组成的文本模式,该模式描述在查找字符串主体时待匹配的一个或者多个字符串.正则表达式作为一个模板,将某个字符模式与所搜索的字符串进行匹配. 普通字符包括所有的大小写字母字符.所有数字.所有标点符号及一些特殊符号.普通字符本身可以组成一个正则表达式,也可以和元字符组合组成一个正则表达式:而元字符则具有特殊的含义,包括().[].{}./.^.$.*.+.?...|.-.?:.?=.?! 2.基本语法 3.优先权含义 二.使用

Java学习笔记_18_字符串、包装类、原始数据类剪得转换

18. 字符串.包装类.原始数据类剪得转换: 各个转换如下: 1>String 转换成Integer: Integer integer = new Integer("string");或 Integer Integer = Integer.valueOf(String): 注:String必须是数字字符串,如:"1232". 2>Integer 转换成String: String str = Integer.toString(); 3>Intege

【Unity 3D】学习笔记二十八:unity工具类

unity为开发者提供了很多方便开发的工具,他们都是由系统封装的一些功能和方法.比如说:实现时间的time类,获取随机数的Random.Range( )方法等等. 时间类 time类,主要用来获取当前的系统时间. using UnityEngine; using System.Collections; public class Script_04_13 : MonoBehaviour { void OnGUI() { GUILayout.Label("当前游戏时间:" + Time.t

JAVA学习笔记(五十二)- 开发DAO层的经典实现

StudentDAO接口,定义学生相关的操作 /* * StudentDAO接口,定义学生相关的操作 */ public interface StudentDAO { //添加学生 public void addStudent(Student stu); //删除学生 public void deleteStudent(int id); //修改学生 public void updateStudent(Student stu); //查询所有学生 public List<Student> ge

JAVA学习笔记(五十三)- 经典三层架构实例

UserDAO接口 /* * UserDAO接口 */ public interface UserDAO { //插入用户 public void insert(User user); //删除用户 public void delete(int id); //更新用户 public void update(User user); //查询所有用户 public List<User> getAllUsers(); //根据用户名或密码查询用户 public boolean checkUser(U

JAVA学习第四十三课 — 集合框架工具类(一)

一.Collections:集合框架的工具类 其中的方法都是静态的 排序方法演示 import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; class ComparaByLeng implements Comparator<String>{ public int compare(String o1, String o2) { int

Java学习笔记(八)&mdash;&mdash;封装

一.封装 1.定义 将类的信息隐藏在类的内部,不允许外部程序直接进行访问,而是通过该类提供的方法来实现对隐藏信息的操作和方法. 2.优点 (1)只能通过规定的方法访问数据 (2)隐藏类的细节,方便修改和实现. 3.封装的实现步骤 (1)修改属性的可见性(private) (2)创建getter/setter方法(属性的读写) (3)在getter/setter方法放入控制语句 4.一个demo package com.cnblogs; public class Telphone { privat