五、Jdbc的使用

JDBC規(guī)范

持久化的概念

  • 將程序中的數(shù)據(jù)保存到硬盤、U盤等可掉電式硬件中

為什么要使用JDBC規(guī)范?

  • 在JDBC規(guī)范出來之前,各大數(shù)據(jù)庫廠商使用自己的操作數(shù)據(jù)庫的規(guī)范,使得廣大開發(fā)者難以操作數(shù)據(jù)庫,心力憔悴,開發(fā)成本增大;直到Sun公司統(tǒng)一了各個操作數(shù)據(jù)庫的接口規(guī)范,迎來了開發(fā)者的新生;而這套操作關(guān)系型數(shù)據(jù)庫的規(guī)范就是JDBC規(guī)范,極大地減少了開發(fā)成本

JDBC的基本操作

  • 加載mysql驅(qū)動
    Class.forName("com.mysql.jdbc.Driver");
    
  • 獲取連接對象
    Connection conn = DriverManager.getConnection(
        //url
        "jdbc:mysql://127.0.0.1/jdbc:3306?characterEncoding=utf-8&useSSL=false",
        //數(shù)據(jù)庫用戶名
        "root",
        //數(shù)據(jù)庫密碼
        "root"
        );
    
  • 獲取語句對象
    PreparedStatement pst = conn.prepareStatement(sql);
    
  • 執(zhí)行sql語句
    //sql語句
    String sql = "insert into t_students values (null, ?,?,?,?,?,?,?,?,?)";
    //設(shè)置參數(shù)值
    pst.setString(1, student.getUserName());
    pst.setBoolean(2, student.getSex());
    pst.setDate(3, new java.sql.Date(student.getBirthday().getTime()));
    pst.setBigDecimal(4, student.getSalary());
    pst.setBigDecimal(5, student.getBalance());
    pst.setString(6, student.getCollege());
    pst.setString(7, student.getMajor());
    pst.setString(8, student.getHobby());
    pst.setInt(9, student.getClassRoom());
    //執(zhí)行sql語句,返回數(shù)據(jù)庫表中數(shù)據(jù)的影響條數(shù)
    int result = pst.executeUpdate();
    
  • 釋放資源
    pst.close();
    conn.close();
    

DAO思想

概念

  • 通過編寫一套接口和對應(yīng)實現(xiàn)類的組件來完成對數(shù)據(jù)庫的操作

DAO思想出現(xiàn)的意義

  • 解耦,類與類之間的關(guān)聯(lián)更清晰,使程序更易維護

使用JDBC規(guī)范和DAO思想實現(xiàn)CRUD的步驟

  1. 按照規(guī)范定義包(domain、dao、dao/impl、util、test)
  2. 在domain中定義JavaBean對象,對象屬性和數(shù)據(jù)庫表中字段一一對應(yīng)
  3. 在dao包中按照IXxxDAO規(guī)范定義接口,接口中編寫操作數(shù)據(jù)庫的抽象方法
  4. 在impl中按照XxxDAOImpl的規(guī)范定義dao包中接口的實現(xiàn)類并編寫操作數(shù)據(jù)庫的語句
  5. 在test包中按照規(guī)范定義測試impl包中類的實現(xiàn)類,并使用@Test注解編寫測試方法

提取工具類

  • 將impl實現(xiàn)類中操作數(shù)據(jù)庫的重復(fù)語句提取出來并在util包中定義工具類
  • 將加載驅(qū)動、獲取數(shù)據(jù)庫連接對象的語句編寫在工具類的static靜態(tài)代碼塊中
  • 將釋放資源等重復(fù)語句編寫在工具類中定義工具方法

Jdbc工具類

  • jdbc.properties文件
    driverClassName=com.mysql.jdbc.Driver
    url=jdbc:mysql:///mybatis?characterEncoding=utf-8&useSSL=false
    username=root
    password=root
    
  • JdbcUtils類
    public class JDBCUtils {
    
        private JDBCUtils() {}
    
        public static DataSource dataSource = null;
    
        public static Properties properties = new Properties();
    
        /**
        * 加載jdbc.properties文件,讀取到properties對象中
        */
        static {
            InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
    
            try {
                properties.load(in);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        /**
        * 使用Druid連接池工廠創(chuàng)建連接池對象
        * @return 連接池對象
        */
        public static DataSource getDataSource() {
            try {
                if (dataSource == null) {
                    dataSource = DruidDataSourceFactory.createDataSource(properties);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return dataSource;
        }
    
        /**
        * 釋放資源
        * @param conn
        * @param pst
        * @param rs
        */
        public static void close(Connection conn, PreparedStatement pst, ResultSet rs) {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (pst != null) {
                    pst.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    
        /**
        * 釋放資源
        * @param conn
        * @param pst
        */
        public static void close(Connection conn, PreparedStatement pst) {
            close(conn, pst, null);
        }
    
    }
    
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • JDBC學(xué)習(xí) JAVA Database Connectivity java 數(shù)據(jù)庫連接 為什么會出現(xiàn)JDBC S...
    須臾之北閱讀 147評論 0 1
  • JDBC總結(jié): 1.jdbc入門 2.抽取工具類 3.jdbc與java代碼聯(lián)系的基本sql語句操作 4.JDBC...
    牛倩賤閱讀 567評論 0 0
  • JDBC基礎(chǔ)持久化:把數(shù)據(jù)存到可掉電式存儲設(shè)備中以供以后使用JDBC:Java Database Connecti...
    funOfFan閱讀 233評論 0 0
  • 今天感恩節(jié)哎,感謝一直在我身邊的親朋好友。感恩相遇!感恩不離不棄。 中午開了第一次的黨會,身份的轉(zhuǎn)變要...
    余生動聽閱讀 10,798評論 0 11
  • 彩排完,天已黑
    劉凱書法閱讀 4,453評論 1 3

友情鏈接更多精彩內(nèi)容