oracle學習筆記(六) JDBC使用

JDBC使用

1. 導包

直接使用IDEA導入依賴包便可 新建一個lib,把jar包放在這裏 html

2. 加載驅動

Class.forName("oracle.jdbc.driver.OracleDriver");

3. 建立Connection對象

鏈接數據庫,從而得到Connection對象java

String url = "jdbc:oracle:thin:@localhost:1521:ORCL";//具體的實例名能夠查看本身的服務管理,有個
Connection conn = DriverManager.getConnection(url,"scott","tiger");//後面的兩個參數分別爲鏈接數據庫的用戶名和密碼

PS:查看實例名sql

  1. 開始->運行->輸入services.msc
  2. 找到服務
  3. 後面的就是咱們的oracle數據庫的實例名

4. 建立Statement對象

Statement stmt = conn.createStatement();
  • Statement: 普通語句類型,只能執行一條完整的語句
  • PreparedStatement: 預編譯語句,它支持佔位符「?」, 如:select * from emp WHERE ename LIKE ? and sal>?
  • CallableStatement: 支持存儲過程的調用

PreparedStatementCallableStatement都是繼承Statement,比Statement要強大 補充連接: PreparedStatement的使用 CallableStatement的使用(待補充)數據庫

5. 執行SQL語句

//執行查詢語句,會返回有個結果集ResultSet
ResultSet rs = stmt.executeQuery("select * from student");

6. 使用ResultSet獲取數據庫數據

//遍歷結果集, 每次調用next方法時會使結集的遊標後移,最初遊標位於第一行以前
//Student累是咱們寫的一個bean類,就是把數據庫中的每一條數據看成爲一個對象,每一列都看成爲Student類的屬性
while (rs.next()){ 
	//第循環一次封裝一條記錄
	Student student = new Student();
	student.setNum(rs.getInt("num"));
	student.setName(rs.getString("name"));
	//獲取其它字段rs.getXxx("列名") Xxx表示相應的數據類型
	//或者也能夠re.getXxx(int columnNum) 參數爲第幾列
	//若是不知道列的具體類型,也可使用rs.getObject
}

oracle與java的類型對應oracle

oracle java
varchar/varchar(2) String
int int
number double
date date

7. 關閉

依次關閉ResultSet Statement Connection工具

補充

  • 通常將鏈接方法和關閉方法封裝爲靜態方法調用,鏈接方法和關閉方法封裝在JdbcUtil工具類中編碼

  • 開啓數據庫連接的三個參數通常咱們不會更改,因此咱們直接寫死在資源文件裏面url

    1. 設置編碼UTF-8,使用中文字符就會自動轉爲Unicode spa

    2. ResourceBundle文件通常要在src同目錄,不然會出現java.lang.NoClassDefFoundError異常,代碼以下3d

      jdbc.url = jdbc:oracle:thin:@localhost:1521:ORCL
      	jdbc.driver = oracle.jdbc.driver.OracleDriver
      	jdbc.username = stars
      	jdbc.password = stars

    ResourceBundle bundle = ResourceBundle.getBundle("資源文件名");
      String s = bundle.getString("keyName");//getString("username")..
      }
  • 寫一個Dao類,其中有update,save,delete,find等方法,從而實現對數據庫的增刪改查

JdbcUtil工具類:

package homework;

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

/**
 * @author StarsOne
 * @date Create in  2019/4/24 0024 22:18
 * @description
 */
class JdbcUtil {
    private static final String DRIVER = getValue("jdbc.driver");
    private static final String URL = getValue("jdbc.url");
    private static final String USERNAME = getValue("jdbc.username");
    private static final String PASSWORD = getValue("jdbc.password");

    static{
        try {
            //註冊數據庫驅動程序
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            System.err.println("註冊數據庫驅動程序失敗。" + e.getMessage());
        }
    }

    /**
     * 獲取數據庫鏈接
     * @return 一個Connection
     */
    public static Connection getConnection() {
        try {
            Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            return  conn;
        } catch (SQLException e) {
            System.err.println("a得到數據鏈接失敗。" + e.getMessage());
        }
        return null;
    }


    /**
     * 關閉
     * @param conn
     * @param stmt
     * @param rs
     */
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        try {
            //關閉數據庫的資源的順序最好與使用的順序相反
            if(rs != null){
                rs.close();
            }
            if(stmt != null){
                stmt.close();
            }
            if(conn != null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 讀取屬性文件中的信息
     *
     * @param key
     * @return
     */
    private static String getValue(String key) {
        // 資源包綁定
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
        return bundle.getString(key);
    }


    public static void main(String[] args) {
        System.out.println(getValue("jdbc.driver"));
        System.out.println(getConnection());
    }
}

StudentDao.java

個人代碼尚未補全,使用的Statement語句

package homework;

import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @author StarsOne
 * @date Create in  2019/4/24 0024 22:24
 * @description
 */
class StudentDao {


    /**
     * 添加一個
     * @param student
     */
    public void save(Student student) {
        String name = student.getName();
        int num = student.getNum();
        Connection connection = null;
        Statement statement = null;
        try {
            connection = JdbcUtil.getConnection();

            statement = connection.createStatement();

            //拼接SQL語句,把數據插入到數據庫中
            statement.execute("insert into STUDENT value(" + num + "," + name + ") ");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(connection, statement, null);
        }
    }

    public void update(Student student) {

    }

    /**
     * 刪除指定編號的學生
     * @param num
     */
    public void delete(Integer num) {

        Connection connection = null;
        Statement statement = null;
        try {
            connection = JdbcUtil.getConnection();

            statement = connection.createStatement();

            //拼接SQL語句,把數據插入到數據庫中
            boolean flag = statement.execute("delete from  STUDENT where num = " + num);
            if (flag) {
                System.out.println("刪除成功!");
            } else {
                System.out.println("刪除失敗!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(connection, statement, null);
        }
    }
    /**
     * 主鍵查詢
     * @param number
     */
    public void findByPK(Integer number) {

        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet=null;
        try {
            connection = JdbcUtil.getConnection();

            statement = connection.createStatement();

            //查詢query,返回一個數據集
             resultSet = statement.executeQuery("select * from STUDENT where num =" + number);
            while (resultSet.next()) {
                int num = resultSet.getInt("num");
                String name = resultSet.getString("name");
                String sex = resultSet.getString("sex");
                int age = resultSet.getInt("age");
                Date birthdate = resultSet.getDate("birthdate");
                double grade = resultSet.getDouble("grade");
                //新建一個對象
                new Student(num, age, grade, name, sex, birthdate);

            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(connection, statement, resultSet);
        }
    }

    /**
     * 查詢所有
     * @return
     */
    public List<Student> findAll() {
        List<Student> list = new ArrayList<>();
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet=null;
        try {
            connection = JdbcUtil.getConnection();

            statement = connection.createStatement();

            //查詢query,返回一個數據集
            resultSet = statement.executeQuery("select * from STUDENT" );
            while (resultSet.next()) {
                int num = resultSet.getInt("num");
                String name = resultSet.getString("name");
                String sex = resultSet.getString("sex");
                int age = resultSet.getInt("age");
                Date birthdate = resultSet.getDate("birthdate");
                double grade = resultSet.getDouble("grade");
                //新建一個對象
                list.add(new Student(num, age, grade, name, sex, birthdate));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(connection, statement, resultSet);
        }
        return list;
    }

}

原文出處:https://www.cnblogs.com/stars-one/p/10770470.html

相關文章
相關標籤/搜索