程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> Java Dao模式通過JDBC連接數據庫的操作,daojdbc

Java Dao模式通過JDBC連接數據庫的操作,daojdbc

編輯:JAVA綜合教程

Java Dao模式通過JDBC連接數據庫的操作,daojdbc


Java程序訪問數據庫:

1、獲取數據庫廠商提供的驅動(jdbc接口的實現類)

如ojdbc14.jar——Oracle數據庫驅動jar包

mysql-connector-java-5.1.8-bin.jar——MySQL數據庫驅動jar包

自己去網上下載就行。

2、使用JDBC的API訪問數據庫

連接、SQL語句執行、結果

java.sql.Driver:各個數據庫廠商需要實現該接口,驅動的標記

java.sql.Connection:封裝和數據庫的連接

java.sql.Statement:封裝需要執行的SQL語句

java.sql.ResultSet:封裝查詢的結果集

3、JDBC編程步驟 

step1——加載驅動

step2——獲取連接對象

step3——執行SQL語句

step4——處理結果集

step5——關閉資源

4、下面給出連接數據庫的工具類(自己寫的連接MySql數據庫,如要連接Oeacle可修改對應參數)

package com.day03;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class ConnectionUtils {

    // 線程單例
    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
    private static String url;
    private static String driver;
    private static String username;
    private static String password;

    static {
        Properties props = new Properties();
        try {
            // 從屬性文件中讀取數據庫配置信息,以加載類的方式加載配置文件
            props.load(
                    ConnectionUtils.class.getClassLoader()
                    .getResourceAsStream("com/day03/db_mysql.properties"));

        } catch (IOException e) {
        }
        if (props != null) {
            url = props.getProperty("url");
            driver = props.getProperty("driver");
            username = props.getProperty("username");
            password = props.getProperty("password");

            // 裝載並注冊數據庫驅動
            try {
                Class.forName(driver);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    public static Connection getConnection() throws SQLException {
        Connection con = tl.get();
        if (con == null) {
            con = DriverManager.getConnection(url, username, password);
            tl.set(con);
        }
        return con;
    }

    public static void closeConnection() {
        Connection con = tl.get();
        try {
            if (con != null) {
                con.close();
                tl.set(null);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void closeStatement(Statement stmt) {
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void closeResultSet(ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    public static void closeAll(Statement stmt, ResultSet rs){
        closeConnection();
        closeStatement(stmt);
        closeResultSet(rs);
    }
    
    public static void main(String[] args) throws Exception{
        System.out.println(ConnectionUtils.getConnection());
    }

}

5、配置參數文件db_mysql.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=root

6、Dao模式操作數據庫下面是代碼示例

1)Emp.java

//實體類
public class Emp {
    private int id;
    private String name;
    private double salary;
    public int getId() {
        return id;
    }
    @Override
    public String toString() {
        return "Emp [id=" + id + ", name=" + name + ", salary=" + salary + "]";
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
    public Emp(int id, String name, double salary) {
        super();
        this.id = id;
        this.name = name;
        this.salary = salary;
    }
    public Emp() {
        super();
    }
    public Emp(String name, double salary) {
        super();
        this.name = name;
        this.salary = salary;
    }
}

2)Dao接口類

import java.util.List;

public interface EmpDao {
    List<Emp> findAllEmp() throws Exception;
}

3)工廠類

public class EmpDaoFactory {
    // 讀取文件中實現類的類名,通過反射實例化
    public static EmpDao getEmpDao(){
        return new EmpDaoMySQL();
    }
}

4)Dao接口實現類

public class EmpDaoMySQL implements EmpDao{
    public static final String FIND_ALL_EMP = "select * from t_emp";//查詢語句
    
    public List<Emp> findAllEmp() throws Exception{
        List<Emp> empList = new ArrayList<Emp>();
        Connection conn = ConnectionUtils.getConnection();
        PreparedStatement stmt = conn.prepareStatement(FIND_ALL_EMP);
        ResultSet rs = stmt.executeQuery();
        while(rs.next()){
            int id = rs.getInt(1);
            String name = rs.getString(2);
            double salary = rs.getDouble(3);
            Emp emp = new Emp(id, name, salary);
            empList.add(emp);
        }
        ConnectionUtils.closeAll(stmt, rs);
        return empList;
    }
}

5)測試類

public class EmpBiz {
    public static void main(String[] args) throws Exception{
        EmpDao dao = EmpDaoFactory.getEmpDao();
        List<Emp> empList = dao.findAllEmp();
        for(Emp e : empList){
            System.out.println(e);
        }
    }
}

到此基本實現了Dao模式通過JDBC操做數據庫了。

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved