1. 程式人生 > 實用技巧 >Java使用jdbc連線資料庫

Java使用jdbc連線資料庫

  1. 首先需要獲取資料庫驅動的 jar 包,然後可以通過使用Class.forname(“com.mysql.cj.jdbc.Driver”);來載入驅動 這個是最新版的jdbc驅動連線方式,而之前老版本的驅動則需要將com.mysql.cj.jdbc.Driver 換成 com.mysql.jdbc.Driver 即可,在此,我使用的是最新版本的jdbc驅動。
  2. 載入並獲取驅動
    static {
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
  3. 建立Connection物件,在此通過建立一個方法,以便對以後建立該物件時更加的方便,快捷
    public static Connection getCon() {
            Connection con = null;
            try {
                con = DriverManager.getConnection("jdbc:mysql://localhost/demo?serverTimezone=GMT", "root", "admin");//demo為要獲取的資料庫名,root為的使用者名稱,admin為使用者的登入密碼
    //因為在最新版本的jdbc驅動當中,獲取connection時 需要將資料庫地址,也就是jdbc:mysql://localhost/demo 後,加上 ?serverTimezone=GMT 否則會出現時區錯誤。 }
    catch (SQLException throwables) { throwables.printStackTrace(); } return con; }
  4. 建立一個關閉Connection,prepareStatement以及ResultSet方法,這樣就能避免以後多次呼叫這些方法而反覆寫重複的程式碼
        public static void closeAll(Connection con,PreparedStatement pstmt,ResultSet rels) {
            if(con!=null){
                
    try { con.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(pstmt!=null){ try { pstmt.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(rels!=null){ try { rels.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } }
  5. 建立prepareStatement來操縱SQL語句,也可以使用Statement來操縱SQL語句,因為使用Statement的話,會有SQL注入的風險,所以在此,使用廣泛並且安全的prepareStatement來操縱SQL。
        public static void main(String[] args) {
            Connection con = getCon();//獲取Connection物件
            String sql = "select * from student where id=?";//建立要執行的SQL語句
            PreparedStatement preparedStatement = null;//建立一個空的prepareStatement物件
            ResultSet resultSet = null;//建立ResultSet來接收執行SQL後返回過來的記錄值
            try {
                preparedStatement = con.prepareStatement(sql);//通過Connection的prepareStatement方法來獲取執行SQL後的一個prepareStatement物件
       prepareStatement.setString("1001");//設定where條件id的值 resultSet
    = preparedStatement.executeQuery();//通過獲取到的prepareStatement的executeQuery方法來執行SQL查詢,並返回一個結果集Resultset物件 while (resultSet.next()) {//通過resultSet的next()方法,來判斷是否還存在記錄,返回值為Boolean值
    //輸出student表中,id為1001的記錄值。 System.out.println(resultSet.getString(
    1) + " " + resultSet.getString(2) + " " + resultSet.getString(3) + " " + resultSet.getString(4) + " " + resultSet.getString(5) + " " + resultSet.getString(6) + " "); } } catch (SQLException throwables) { throwables.printStackTrace(); } finally { closeAll(con,prepareStatement,resultSet); } }