1. 程式人生 > >java-Eclipse中使用JDBC連接數據庫

java-Eclipse中使用JDBC連接數據庫

名稱 tst tor tab ase fin from try ...

準備工作:mysql-connector-java-5.1.6-bin.jar配置


package com.job; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class yy { // JDBC 驅動器名稱 和數據庫地址 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; //數據庫的名稱為 EXAMPLE static final String DB_URL = "jdbc:mysql://localhost/EXAMPLE"; // 數據庫用戶和密碼 static final String USER = "root"; static final String PASS = "123456"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ //註冊JDBC 驅動程序 Class.forName("com.mysql.jdbc.Driver"); //打開連接 System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //執行查詢 System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT id, name, age FROM Students"; ResultSet rs = stmt.executeQuery(sql); //得到和處理結果集 while(rs.next()){ //檢索 int id = rs.getInt("id"); int age = rs.getInt("age"); String name = rs.getString("name"); //顯示 System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", Name: " + name); System.out.println(); } //清理環境 rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ // JDBC 操作錯誤 se.printStackTrace(); }catch(Exception e){ // Class.forName 錯誤 e.printStackTrace(); }finally{ //這裏一般用來關閉資源的 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ } try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } System.out.println("Goodbye!"); } }

java-Eclipse中使用JDBC連接數據庫