千鋒逆戰班,jdbc裏面的ORM和DAO

學習java第43天
努力努力在努力,堅持堅持在堅持!

mysql代碼建表

CREATE TABLE `user`(
	user_id INT PRIMARY KEY,
	user_name VARCHAR(20) UNIQUE NOT NULL,
	user_pwd VARBINARY(20) NOT NULL,
	user_borndate DATE,
	user_email VARCHAR(20) NOT NULL,
	user_address VARBINARY(20) NOT NULL
	

)CHARSET=utf8;
INSERT INTO USER VALUES(1,'大白','123','2020-02-02','caom.qf','北京天安門')\
INSERT INTO USER VALUES(2,'小黑','123','2019-01-19','caom.qf','南京')

ALTER TABLE USER MODIFY user_address VARCHAR(20)
SELECT * FROM USER

ORM實體類User

package com.qf.day3.t2;

import java.util.Date;

public class User {
    private int id;
    private String username;
    private String password;
    private Date borndate;
    private String email;
    private String address;

    public User() {
    }

    public User(int id, String username, String password, Date borndate, String email, String address) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.borndate = borndate;
        this.email = email;
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", borndate=" + borndate +
                ", email='" + email + '\'' +
                ", address='" + address + '\'' +
                '}';
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setUsername(String username) {
        this.username = username;
    }

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

    public void setBorndate(Date borndate) {
        this.borndate = borndate;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getId() {
        return id;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public Date getBorndate() {
        return borndate;
    }

    public String getEmail() {
        return email;
    }

    public String getAddress() {
        return address;
    }
}

DAO(數據訪問對象)

package com.qf.day3.t3;

import com.qf.day3.t2.DBUtils;
import com.qf.day3.t2.User;
import com.qf.day3.t4.DateUtiles;

import javax.jws.soap.SOAPBinding;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 對數據庫中User表的一系列操作。
 * 只做對數據庫訪問的操作!\
 * 複用! 對同一張表的操作 實現複用
 */
public class UserDaoImpl {
    private Connection conn = null;
    private PreparedStatement pre = null;
    private ResultSet re = null;

    //增
    public int insert(User user) {
        conn = DBUtils.getConnection();
        String sql = "insert into user(user_id,user_name,user_pwd,user_borndate,user_email,user_address) values (?,?,?,?,?,?)";
        try {
            pre = conn.prepareStatement(sql);
            pre.setInt(1, user.getId());
            pre.setString(2, user.getUsername());
            pre.setString(3, user.getPassword());
            pre.setDate(4, DateUtiles.utilToSql(user.getBorndate()));
            pre.setString(5, user.getEmail());
            pre.setString(6, user.getAddress());
            int i = pre.executeUpdate();
            return i;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.closeAll(conn, pre, re);
        }

        return 0;
    }

    //刪
    public int delete(int id) {
        conn = DBUtils.getConnection();
        String sql = "delete from user where user_id = ?";

        try {
            pre = conn.prepareStatement(sql);
            pre.setInt(1, id);
            int i = pre.executeUpdate();
            return i;

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.closeAll(conn, pre, re);
        }

        return 0;
    }

    //改
    public int upDate(User user) {
        conn = DBUtils.getConnection();
        String sql = "update user set user_name = ?,user_pwd = ?,user_borndate=?,user_email = ?,user_address=? where user_id =?";
        try {
            pre = conn.prepareStatement(sql);
            pre.setString(1, user.getUsername());
            pre.setString(2, user.getPassword());
            pre.setDate(3, DateUtiles.utilToSql(user.getBorndate()));
            pre.setString(4, user.getEmail());
            pre.setString(5, user.getAddress());
            pre.setInt(6, user.getId());
            int i = pre.executeUpdate();
            return i;

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.closeAll(conn, pre, re);
        }
        return 0;
    }

    //查單個
    public User select(int id) {
        conn = DBUtils.getConnection();
        String sql = "select user_id,user_name,user_pwd,user_borndate,user_email,user_address from user where user_id=?";
        try {
            pre = conn.prepareStatement(sql);
            pre.setInt(1, id);
            re = pre.executeQuery();
            if (re.next()) {//這句不能省(re.next())
                int uid = re.getInt("user_id");
                String name = re.getString("user_name");
                String password = re.getString("user_pwd");
                java.util.Date date = re.getDate("user_borndate");
                String email = re.getString("user_email");
                String address = re.getString("user_address");

                return new User(uid, name, password, date, email, address);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.closeAll(conn, pre, re);
        }
        return null;
    }

    //查所有
    public List<User> selectAll() {
        conn = DBUtils.getConnection();
        List<User> userList = new ArrayList<User>();
        String sql = "select user_id,user_name,user_pwd,user_borndate,user_email,user_address from user ";

        try {
            pre = conn.prepareStatement(sql);
            re = pre.executeQuery();

            while(re.next()){
                int uid = re.getInt(1);
                String name = re.getString(2);
                String pwd = re.getString(3);
                java.util.Date date = re.getDate(4);
                String email = re.getString(5);
                String address = re.getString(6);
                User user = new User(uid,name,pwd,date,email,address);
                userList.add(user);

            }
            return userList;

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtils.closeAll(conn,pre,re);
        }


        return null;


    }
}

測試代碼

package com.qf.day3.t3;

import com.qf.day3.t2.User;
import com.qf.day3.t4.DateUtiles;

import java.util.List;

public class TestUser {
    public static void main(String[] args) {
        UserDaoImpl udi = new UserDaoImpl();
//        User user = new User(3,"泰羅","123", DateUtiles.strToUtil("2010-10-10"),"qq.com","m78星雲");
//        int reslut = udi.insert(user);
//        System.out.println(reslut);

//        System.out.println(udi.select(2));

        List<User> l = udi.selectAll();
        l.forEach(System.out::println);

    }
}

日期從util.Date到sql.Date轉換類

package com.qf.day3.t4;

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class DateUtiles {
    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    //字符串轉java.util.Date
    public static java.util.Date strToUtil(String str){
        try {
           return simpleDateFormat.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;

    }
//str轉換成sql
    public static java.sql.Date strToSql(String str){

        return utilToSql(strToUtil(str));

    }
    //util轉換成sql
    public static java.sql.Date utilToSql(java.util.Date date){

        return new java.sql.Date(date.getTime());
    }


}

註冊驅動,獲取數據庫連接,釋放資源,根據配置文件的參數來獲取的

package com.qf.day3.t2;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 數據庫工具類
 * 1、獲取連接 connection
 * 2、釋放資源
 * 可跨平臺方案
 */
public class DBUtils {
    private static final Properties properties = new Properties();

    static {
        try {
            InputStream is = DBUtils.class.getResourceAsStream("/db.properties");
            properties.load(is);//通過流將文件中的內容分割成鍵值對

            Class.forName(properties.getProperty("driver"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    public static Connection getConnection(){
        Connection conn = null;

        try {
            conn = DriverManager.getConnection(properties.getProperty("url"),properties.getProperty("username"),properties.getProperty("password"));
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return conn;
    }
    //釋放資源
    public static void closeAll(Connection conn, Statement st, ResultSet re){
        try {
            if(conn != null){
                conn.close();
            }
            if(st != null){
                st.close();
            }
            if(re != null){
                re.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章