jdbc小項目

目標

  • 數(shù)據(jù)庫工具類 DBUtil
  • 工具類測試
  • 建包蚓再、接口摘仅、實現(xiàn)類架構
  • 研究功能问畅,畫流程圖
  • 建表

數(shù)據(jù)庫工具類

位置 com.neuedu.utils.DBUtil.java

連接數(shù)據(jù)庫的方法 getConnection

    public static Connection getConnection() {
            Connection conn=null;
                try {
                    //1)加載驅動
                    Class.forName("com.mysql.jdbc.Driver");
                    //2)連接準備
                    String url="jdbc:mysql://localhost:3306/scott";
                    String user="root";
                    String password="root";
                    //3)獲取連接
                    conn=DriverManager.getConnection(url, user, password);
                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    System.out.println(e.getMessage());
                    e.printStackTrace();
                } catch (SQLException e) {
                    System.out.println(e.getMessage());
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } 
            return conn;
        }

關閉連接的方法 CloseConnection

public  static void closeConnection(ResultSet rs, PreparedStatement pst, Connection conn) {
    try {
        if(null!=rs){
        rs.close();
        }
        if(null!=pst){
        pst.close();
        }
        if(null!=conn){
        conn.close();
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

相關測試類

public static void main(String[] args) {
    Connection conn=DBUtils.getConnection();
    PreparedStatement pst=null;
    ResultSet rs=null;
    System.out.println(conn);
    try {
        pst=conn.prepareStatement("select * from dept");
        rs=pst.executeQuery();
        while(rs.next()){
            System.out.println(rs.getString("dname"));
        }
        
        
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally {
        //關閉連接
        DBUtils.closeConnection(rs,pst,conn);
    
    }
}

建包

com.neuedu.dao---放接口
com.neuedu.dao.impl---放接口的實現(xiàn)類

image.png

流程圖

image.png

建表語句

drop table if exists tab_user;

/*==============================================================*/
/* Table: tab_user  */
/*==============================================================*/
create table tab_user
(
   id   varchar(32) not null,
   username varchar(20),
   password varchar(20),
   emailvarchar(50),
   role varchar(1),
   birthday date,
   primary key (id)
);

實體類

com.neuedu.pojo---放實體類

package com.neuedu.pojo;

/**
 * 用戶信息表
 * 
 * @author wang.qj@neusoft.com
 *
 */
public class TabUser {
    // 用戶主鍵id
    private String id;
    // 用戶名
    private String userName;
    // 密碼
    private String password;
    // 郵箱
    private String email;
    // 角色
    private String role;
    // 生日
    private String birthday;

    public String getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

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

    public String getEmail() {
        return email;
    }

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

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public String getBirthday() {
        return birthday;
    }

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

}

dao接口

package com.neuedu.dao;

import java.util.List;

import com.neuedu.pojo.TabUser;
/**
 * 用戶管理接口
 * @author Administrator
 *
 */
public interface IUserDao {
    //添加用戶方法
   public int addUser(TabUser user);
   //根據(jù)用戶名密碼查詢用戶信息卵皂,用于鑒權
   public TabUser getUserByNameAndPwd(String name,String pwd);
   //修改用戶信息
   public int updateUser(TabUser user);
   //根據(jù)主鍵id刪除用戶信息
   public int delUserById(String id);
   //根據(jù)ID查詢用戶信息(因為id為主鍵灯变,所以返回單用戶)
   public TabUser getUserById(String id);
   //根據(jù)姓名查詢用戶信息(假設:用戶名可以重復,如果用戶名不可以重復就可以返回單用戶TabUser)
   public List<TabUser> getUserByName(String name);
   //查詢所有
   public List<TabUser> getAll();
   
}

dao實現(xiàn)類

package com.neuedu.dao.impl;

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

import com.neuedu.dao.IUserDao;
import com.neuedu.pojo.TabUser;
import com.neuedu.utils.DBUtils;
import com.neuedu.utils.DateUtils;
import com.neuedu.utils.UUIDGenerateUtils;

public class UserDaoImpl implements IUserDao {
    // 前三個必寫滚粟,用新寫的工具類凡壤,后四個選寫
    @Override
    public int addUser(TabUser user) {
        // 獲取連接
        Connection conn = DBUtils.getConnection();
        PreparedStatement pst = null;
        int i = 0;
        try {
            // 假設用戶輸入的生日格式 為yyyy-MM-dd
            // 把用戶輸入的字符串型的日期轉換成java.sql.Date
            // 考慮到以后會經常用到耙替,所以做一個工具類
            java.sql.Date birthday = DateUtils.getDateFromStr(user.getBirthday());
            // 預處理語句
            pst = conn.prepareStatement("insert into tab_user values(?,?,?,?,?,?)");
            pst.setString(1, UUIDGenerateUtils.getUUID());
            pst.setString(2, user.getUserName());
            pst.setString(3, user.getPassword());
            pst.setString(4, user.getEmail());
            pst.setString(5, user.getRole());
            pst.setDate(6, birthday);
            i = pst.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            DBUtils.closeConnection(null, pst, conn);
        }
        return i;
    }

    @Override
    public int updateUser(TabUser user) {
        // 獲取連接
        Connection conn = DBUtils.getConnection();
        PreparedStatement pst = null;
        int i = 0;
        try {
            // 假設用戶輸入的生日格式 為yyyy-MM-dd
            // 把用戶輸入的字符串型的日期轉換成java.sql.Date
            // 考慮到以后會經常用到硝烂,所以做一個工具類
            java.sql.Date birthday = DateUtils.getDateFromStr(user.getBirthday());
            // 預處理語句
            pst = conn.prepareStatement(
                    "update tab_user set userName=?,password=?,email=?,role=?,birthday=? where id=? ");
            pst.setString(1, user.getUserName());
            pst.setString(2, user.getPassword());
            pst.setString(3, user.getEmail());
            pst.setString(4, user.getRole());
            pst.setDate(5, birthday);
            pst.setString(6, user.getId());
            i = pst.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            DBUtils.closeConnection(null, pst, conn);
        }
        return i;
    }

    @Override
    public int delUserById(String id) {
        // 獲取連接
        Connection conn = DBUtils.getConnection();
        PreparedStatement pst = null;
        int i = 0;
        try {
            // 預處理語句
            pst = conn.prepareStatement("delete from tab_user where id=?");
            pst.setString(1, id);
            i = pst.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            DBUtils.closeConnection(null, pst, conn);
        }
        return i;
    }

    @Override
    public TabUser getUserById(String id) {
        // 獲取連接
        Connection conn = DBUtils.getConnection();
        PreparedStatement pst = null;
        ResultSet rs = null;
        TabUser user = null;
        try {
            // 預處理語句
            pst = conn.prepareStatement("select * from tab_user where id=?");
            pst.setString(1, id);
            rs = pst.executeQuery();
            // 如果有查詢結果钢坦,我們就拼裝一個TabUser類型的對象,返回去
            // if/while if返回一條厨诸,while 有可能多條 因為主鍵不會重復微酬,所以用if
            if (rs.next()) {
                // 實例化對象 大容器
                user = new TabUser();
                user.setUserName(rs.getString("username"));
                user.setId(rs.getString("id"));
                user.setUserName(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setRole(rs.getString("role"));
                user.setBirthday(rs.getString("birthday"));
            }

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            DBUtils.closeConnection(null, pst, conn);
        }
        return user;
    }
   //根據(jù)用戶名查詢颤陶,用戶名可以重復陷遮,返回list
    @Override
    public List<TabUser> getUserByName(String name) {
        // 獲取連接
        Connection conn = DBUtils.getConnection();
        PreparedStatement pst = null;
        ResultSet rs = null;
        List<TabUser> userList=new ArrayList();
        try {
            // 預處理語句
            pst = conn.prepareStatement("select * from tab_user where username=?");
            pst.setString(1, name);
            rs = pst.executeQuery();
            // 如果有查詢結果帽馋,我們就拼裝一個TabUser類型的對象,返回去
            // if/while if返回一條绽族,while 有可能多條 因為主鍵不會重復吧慢,所以用if
            while (rs.next()) {
                // 實例化對象 大容器
                TabUser user = new TabUser();
                user.setId(rs.getString("id"));
                user.setUserName(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setRole(rs.getString("role"));
                user.setBirthday(rs.getString("birthday"));
                userList.add(user);
            }

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            DBUtils.closeConnection(null, pst, conn);
        }
        return userList;
    }

    @Override
    public List<TabUser> getAll() {
        PreparedStatement pst = null;
        ResultSet rs = null;
        List<TabUser> userList=new ArrayList();
        Connection conn=DBUtils.getConnection();
        try {
            pst=conn.prepareStatement("select * from tab_user");
            rs=pst.executeQuery();
            //有可能多列
            while(rs.next()){
                TabUser user=new TabUser();
                user.setId(rs.getString("id"));
                user.setUserName(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setBirthday(rs.getString("birthday"));
                user.setRole(rs.getString("role"));
                userList.add(user);
            }
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return userList;
    }

    @Override
    public TabUser getUserByNameAndPwd(String name, String pwd) {
        // 獲取連接
        Connection conn = DBUtils.getConnection();
        PreparedStatement pst = null;
        ResultSet rs = null;
        TabUser user = null;
        try {
            // 預處理語句
            pst = conn.prepareStatement("select * from tab_user where name=? and password=?");
            pst.setString(1, name);
            pst.setString(2, pwd);
            rs = pst.executeQuery();
            // if/while if返回一條匈仗,while 有可能多條 因為假設用戶名不重復岁诉,所以用if
            if (rs.next()) {
                // 實例化對象 大容器
                user = new TabUser();
                user.setId(rs.getString("id"));
                user.setUserName(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setRole(rs.getString("role"));
                user.setBirthday(rs.getString("birthday"));
            }

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            DBUtils.closeConnection(null, pst, conn);
        }
        return user;
    }

}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末涕癣,一起剝皮案震驚了整個濱河市坠韩,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌音比,老刑警劉巖氢惋,帶你破解...
    沈念sama閱讀 219,366評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件焰望,死亡現(xiàn)場離奇詭異,居然都是意外死亡来屠,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,521評論 3 395
  • 文/潘曉璐 我一進店門捆姜,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人迎膜,你說我怎么就攤上這事×闾В” “怎么了宽涌?”我有些...
    開封第一講書人閱讀 165,689評論 0 356
  • 文/不壞的土叔 我叫張陵卸亮,是天一觀的道長。 經常有香客問我段直,道長溶诞,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,925評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮枉圃,結果婚禮上,老公的妹妹穿的比我還像新娘坎穿。我一直安慰自己返劲,他們只是感情好篮绿,可當我...
    茶點故事閱讀 67,942評論 6 392
  • 文/花漫 我一把揭開白布搔耕。 她就那樣靜靜地躺著,像睡著了一般菩收。 火紅的嫁衣襯著肌膚如雪鲸睛。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,727評論 1 305
  • 那天箱舞,我揣著相機與錄音晴股,去河邊找鬼肺魁。 笑死,一個胖子當著我的面吹牛寂呛,可吹牛的內容都是我干的瘾晃。 我是一名探鬼主播,決...
    沈念sama閱讀 40,447評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼劫拢,長吁一口氣:“原來是場噩夢啊……” “哼尚镰!你這毒婦竟也來了哪廓?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,349評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎哆料,沒想到半個月后东亦,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體唬渗,經...
    沈念sama閱讀 45,820評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡镊逝,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,990評論 3 337
  • 正文 我和宋清朗相戀三年撑蒜,在試婚紗的時候發(fā)現(xiàn)自己被綠了玄渗。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,127評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡浴滴,死狀恐怖巡莹,靈堂內的尸體忽然破棺而出甜紫,到底是詐尸還是另有隱情,我是刑警寧澤腰根,帶...
    沈念sama閱讀 35,812評論 5 346
  • 正文 年R本政府宣布额嘿,位于F島的核電站劣挫,受9級特大地震影響,放射性物質發(fā)生泄漏球拦。R本人自食惡果不足惜帐我,卻給世界環(huán)境...
    茶點故事閱讀 41,471評論 3 331
  • 文/蒙蒙 一拦键、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧芬为,春花似錦、人聲如沸氧敢。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,017評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽半火。三九已至,卻和暖如春梅掠,著一層夾襖步出監(jiān)牢的瞬間店归,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,142評論 1 272
  • 我被黑心中介騙來泰國打工且叁, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人秩伞。 一個月前我還...
    沈念sama閱讀 48,388評論 3 373
  • 正文 我出身青樓逞带,卻偏偏與公主長得像,于是被迫代替她去往敵國和親纱新。 傳聞我的和親對象是個殘疾皇子展氓,可洞房花燭夜當晚...
    茶點故事閱讀 45,066評論 2 355

推薦閱讀更多精彩內容

  • 一. Java基礎部分.................................................
    wy_sure閱讀 3,811評論 0 11
  • 一、編程規(guī)約 (一)命名規(guī)約 【強制】 代碼中的命名均不能以下劃線或美元符號開始脸爱,也不能以下劃線或美元符號結束遇汞。反...
    喝咖啡的螞蟻閱讀 1,511評論 0 2
  • 本文主要內容 1、JDBC 2簿废、DBUtils 01JDBC概念和數(shù)據(jù)庫驅動程序 A: JDBC概念和數(shù)據(jù)庫驅動程...
    勝浩_ae28閱讀 399評論 0 0
  • 一勺疼、背景 Java開發(fā)人員現(xiàn)在對數(shù)據(jù)庫的操作一般會用到諸如像Hibernate,Mybatis,SpringJdb...
    乄墨風閱讀 483評論 0 0
  • 本人的環(huán)境為Myeclipse10捏鱼、MySQL5.7.15 本文包括:簡介JDBC編程步驟打通數(shù)據(jù)庫程序詳解—Dr...
    廖少少閱讀 3,946評論 7 39