Driver 是一個接口: 數(shù)據(jù)庫廠商必須提供實現(xiàn)的接口. 能從其中獲取數(shù)據(jù)庫連接.
可以通過 Driver 的實現(xiàn)類對象獲取數(shù)據(jù)庫連接.
1. 加入 MySQL 驅(qū)動
1). 解壓 mysql-connector-java-5.1.7.zip
2). 在當前項目下新建 lib 目錄
3). 把 mysql-connector-java-5.1.7-bin.jar 復(fù)制到 lib 目錄下
4). 右鍵 build-path , add to buildpath 加入到類路徑下.s
幾種常用數(shù)據(jù)庫的JDBC URL:
@Testpublic void testDriver() throws SQLException { //1. 創(chuàng)建一個 Driver 實現(xiàn)類的對象 Driver driver = new com.mysql.jdbc.Driver(); //2. 準備連接數(shù)據(jù)庫的基本信息: url, user, passWord String url = "jdbc:mysql://localhost:3306/test"; PRoperties info = new Properties(); info.put("user", "root"); info.put("password", "1230"); //3. 調(diào)用 Driver 接口的 connect(url, info) 獲取數(shù)據(jù)庫連接 Connection connection = driver.connect(url, info); System.out.println(connection);}獲取數(shù)據(jù)庫鏈接最簡單方法
/**JDBC.properties文件中的內(nèi)容:#driver=Oracle.jdbc.driver.OracleDriver#jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl#user=scott#password=javadriver=com.mysql.jdbc.DriverjdbcUrl=jdbc:mysql://localhost:3306/atguiguuser=rootpassword=1230*/public Connection getConnection() throws Exception{ String driverClass = null; String jdbcUrl = null; String user = null; String password = null; //讀取類路徑下的 jdbc.properties 文件 InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties"); Properties properties = new Properties(); properties.load(in); driverClass = properties.getProperty("driver"); jdbcUrl = properties.getProperty("jdbcUrl"); user = properties.getProperty("user"); password = properties.getProperty("password"); //通過反射常見 Driver 對象. Driver driver = (Driver) Class.forName(driverClass).newInstance(); Properties info = new Properties(); info.put("user", user); info.put("password", password); //通過 Driver 的 connect 方法獲取數(shù)據(jù)庫連接. Connection connection = driver.connect(jdbcUrl, info); return connection; } @Test public void testGetConnection() throws Exception{ System.out.println(getConnection()); }在不修改源程序的情況下,獲取任何數(shù)據(jù)庫鏈接的通用方法(原始方法)
解決方案: 把數(shù)據(jù)庫驅(qū)動 Driver 實現(xiàn)類的全類名、url、user、password 放入一個
配置文件中, 通過修改配置文件的方式實現(xiàn)和具體的數(shù)據(jù)庫解耦.
@Test public void testDriverManager() throws SQLException, IOException { String driverClass = null; String jdbcUrl = null; String user = null; String password = null; InputStream in = getClass().getClassLoader().getResourceAsStream( "jdbc.properties"); Properties proper = new Properties(); proper.load(in); driverClass = proper.getProperty("driver"); jdbcUrl = proper.getProperty("jdbcUrl"); user = proper.getProperty("user"); password = proper.getProperty("password"); Connection connection = DriverManager.getConnection(jdbcUrl, user, password); System.out.println(connection); }使用DriverManager獲取數(shù)據(jù)庫鏈接的方法
@Test public void testDriverManager() throws ClassNotFoundException, SQLException { String driverClass = "com.mysql.jdbc.Driver"; // String driverClass2 = "oracle.jdbc.driver.OracleDriver"; String jdbcUrl = "jdbc:mysql://localhost:3306/test"; // String jdbcUrl2 = "jdbc:oracle:thin:@localhost:1521:orcl"; String user = "root"; // String user2 = "scott"; String password = "123"; // String password2 = "tiger"; Class.forName(driverClass); Connection connection = DriverManager.getConnection(jdbcUrl, user, password); System.out.println(connection); }更為簡便的使用DriverManager獲取數(shù)據(jù)庫鏈接的方法
1 @Test 2 public void testGetConnection2() throws Exception{ 3 System.out.println(getConnection2()); 4 } 5 6 public Connection getConnection2() throws Exception{ 7 //1. 準備連接數(shù)據(jù)庫的 4 個字符串. 8 //1). 創(chuàng)建 Properties 對象 9 Properties properties = new Properties();10 11 //2). 獲取 jdbc.properties 對應(yīng)的輸入流12 InputStream in = 13 this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");14 15 //3). 加載 2) 對應(yīng)的輸入流16 properties.load(in);17 18 //4). 具體決定 user, password 等4 個字符串. 19 String user = properties.getProperty("user");20 String password = properties.getProperty("password");21 String jdbcUrl = properties.getProperty("jdbcUrl");22 String driver = properties.getProperty("driver");23 24 //2. 加載數(shù)據(jù)庫驅(qū)動程序(對應(yīng)的 Driver 實現(xiàn)類中有注冊驅(qū)動的靜態(tài)代碼塊.)25 Class.forName(driver);26 27 //3. 通過 DriverManager 的 getConnection() 方法獲取數(shù)據(jù)庫連接. 28 return DriverManager.getConnection(jdbcUrl, user, password);29 }獲取數(shù)據(jù)庫連接的最終版本,既解耦又利用到了DriverManager
2、如何通過 JDBC 向指定的數(shù)據(jù)表中插入一條記錄?1. Statement: 用于執(zhí)行 SQL 語句的對象1). 通過 Connection 的 createStatement() 方法來獲取2). 通過 executeUpdate(sql) 可以執(zhí)行 SQL 語句.3). 傳入的 SQL 可以是 INSRET, UPDATE 或 DELETE. 但不能是 SELECT2. Connection、Statement 都是應(yīng)用程序和數(shù)據(jù)庫服務(wù)器的連接資源. 使用后一定要關(guān)閉. 需要在 finally 中關(guān)閉 Connection 和 Statement 對象. 3. 關(guān)閉的順序是: 先關(guān)閉后獲取的. 即先關(guān)閉 Statement 后關(guān)閉 Connection.
@Test public void testStatement() throws Exception{ //1. 獲取數(shù)據(jù)庫連接 Connection conn = null; Statement statement = null; try { conn = getConnection2(); //3. 準備插入的 SQL 語句 String sql = null; // sql = "INSERT INTO customers (NAME, EMAIL, BIRTH) " +// "VALUES('XYZ', '[email protected]', '1990-12-12')";// sql = "DELETE FROM customers WHERE id = 1"; sql = "UPDATE customers SET name = 'TOM' " + "WHERE id = 4"; System.out.println(sql); //4. 執(zhí)行插入. //1). 獲取操作 SQL 語句的 Statement 對象: //調(diào)用 Connection 的 createStatement() 方法來獲取 statement = conn.createStatement(); //2). 調(diào)用 Statement 對象的 executeUpdate(sql) 執(zhí)行 SQL 語句進行插入 statement.executeUpdate(sql); } catch (Exception e) { e.printStackTrace(); } finally{ try { //5. 關(guān)閉 Statement 對象. if(statement != null) statement.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ //2. 關(guān)閉連接 if(conn != null) conn.close(); } } }通過Statement獲取連接,執(zhí)行更新操作(包括insert,update,delete)
public void update(String sql){ Connection conn = null; Statement statement = null; String sql = null; try { conn = JDBCTools.getConnection(); statement = conn.createStatement(); statement.executeUpdate(sql); } catch (Exception e) { e.printStackTrace(); } finally{ JDBCTools.release(statement, conn); } }通用的更新的方法: 包括 INSERT、UPDATE、DELETE(即是要建立一個數(shù)據(jù)庫工具類:獲取數(shù)據(jù)庫連接,關(guān)閉連接)
package com.shellway.jdbc;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;/** * 操作 JDBC 的工具類. 其中封裝了一些工具方法 Version 1 */public class JDBCTools { public static void release(ResultSet rs, Statement statement, Connection conn) { if(rs != null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (statement != null) { try { statement.close(); } catch (Exception e2) { e2.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (Exception e2) { e2.printStackTrace(); } } } /** * 關(guān)閉 Statement 和 Connection * @param statement * @param conn */ public static void release(Statement statement, Connection conn) { if (statement != null) { try { statement.close(); } catch (Exception e2) { e2.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (Exception e2) { e2.printStackTrace(); } } } /** * 1. 獲取連接的方法. 通過讀取配置文件從數(shù)據(jù)庫服務(wù)器獲取一個連接. * * @return * @throws Exception */ public static Connection getConnection() throws Exception { // 1. 準備連接數(shù)據(jù)庫的 4 個字符串. // 1). 創(chuàng)建 Properties 對象 Properties properties = new Properties(); // 2). 獲取 jdbc.properties 對應(yīng)的輸入流 InputStream in = JDBCTools.class.getClassLoader().getResourceAsStream( "jdbc.properties"); // 3). 加載 2) 對應(yīng)的輸入流 properties.load(in); // 4). 具體決定 user, password 等4 個字符串. String user = properties.getProperty("user"); String password = properties.getProperty("password"); String jdbcUrl = properties.getProperty("jdbcUrl"); String driver = properties.getProperty("driver"); // 2. 加載數(shù)據(jù)庫驅(qū)動程序(對應(yīng)的 Driver 實現(xiàn)類中有注冊驅(qū)動的靜態(tài)代碼塊.) Class.forName(driver); // 3. 通過 DriverManager 的 getConnection() 方法獲取數(shù)據(jù)庫連接. return DriverManager.getConnection(jdbcUrl, user, password); }}附上:要建立的數(shù)據(jù)庫工具類:JDBCTools
3、總結(jié):
1、Connection:代表應(yīng)用程序和數(shù)據(jù)庫的一個連接.
2、Statement:是用于操作 SQL 的對象.
3、ResultSet:封裝 JDBC 的查詢結(jié)果.
package com.shellway.jdbc;import java.io.IOException;import java.io.InputStream;import java.security.interfaces.RSAKey;import java.sql.Connection;import java.sql.Date;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;import org.junit.Test;public class ReviewTest { /** * 1. ResultSet 封裝 JDBC 的查詢結(jié)果. */ @Test public void testResultSet(){ Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { //1. 獲取數(shù)據(jù)庫連接 connection = getConnection(); //2. 調(diào)用 Connection 對象的 createStatement() 方法獲取 Statement 對象 statement = connection.createStatement(); //3. 準備 SQL 語句 String sql = "SELECT id, name, email, birth FROM customers"; //4. 發(fā)送 SQL 語句: 調(diào)用 Statement 對象的 executeQuery(sql) 方法. //得到結(jié)果集對象 ResultSet resultSet = statement.executeQuery(sql); //5. 處理結(jié)果集: //5.1 調(diào)用 ResultSet 的 next() 方法: 查看結(jié)果集的下一條記錄是否有效, //若有效則下移指針 while(resultSet.next()){ //5.2 getXxx() 方法獲取具體的列的值. int id = resultSet.getInt(1); String name = resultSet.getString(2); String email = resultSet.getString(3); Date birth = resultSet.getDate(4); System.out.println(id); System.out.println(name); System.out.println(email); System.out.println(birth); System.out.println(); } } catch (Exception e) { e.printStackTrace(); } finally{ //6. 關(guān)閉數(shù)據(jù)庫資源 releaseDB(resultSet, statement, connection); } } /** * 1. Statement 是用于操作 SQL 的對象 */ @Test public void testStatement(){ Connection connection = null; Statement statement = null; try { //1. 獲取數(shù)據(jù)庫連接 connection = getConnection(); //2. 調(diào)用 Connection 對象的 createStatement() 方法獲取 Statement 對象 statement = connection.createStatement(); //3. 準備 SQL 語句 String sql = "UPDATE customers SET name = 'Jerry' " + "WHERE id = 5"; //4. 發(fā)送 SQL 語句: 調(diào)用 Statement 對象的 executeUpdate(sql) 方法 statement.executeUpdate(sql); } catch (Exception e) { e.printStackTrace(); } finally{ //5. 關(guān)閉數(shù)據(jù)庫資源: 由里向外關(guān)閉. releaseDB(null, statement, connection); } } public void releaseDB(ResultSet resultSet, Statement statement, Connection connection){ if(resultSet != null){ try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if(statement != null){ try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if(connection != null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } @Test public void testGetConnection2() throws Exception{ Connection connection = getConnection(); System.out.println(connection); } public Connection getConnection() throws IOException, ClassNotFoundException, SQLException { //0. 讀取 jdbc.properties /** * 1). 屬性文件對應(yīng) Java 中的 Properties 類 * 2). 可以使用類加載器加載 bin 目錄(類路徑下)的文件 */ Properties properties = new Properties(); InputStream inStream = ReviewTest.class.getClassLoader() .getResourceAsStream("jdbc.properties"); properties.load(inStream); //1. 準備獲取連接的 4 個字符串: user, password, jdbcUrl, driverClass String user = properties.getProperty("user"); String password = properties.getProperty("password"); String jdbcUrl = properties.getProperty("jdbcUrl"); String driverClass = properties.getProperty("driverClass"); //2. 加載驅(qū)動: Class.forName(driverClass) Class.forName(driverClass); //3. 調(diào)用 //DriverManager.getConnection(jdbcUrl, user, password) //獲取數(shù)據(jù)庫連接 Connection connection = DriverManager .getConnection(jdbcUrl, user, password); return connection; } /** * Connection 代表應(yīng)用程序和數(shù)據(jù)庫的一個連接. * @throws Exception */ @Test public void testGetConnection() throws Exception{ //1. 準備獲取連接的 4 個字符串: user, password, jdbcUrl, driverClass String user = "root"; String password = "123"; String jdbcUrl = "jdbc:mysql:///test"; String driverClass = "com.mysql.jdbc.Driver"; //2. 加載驅(qū)動: Class.forName(driverClass) Class.forName(driverClass); //3. 調(diào)用 //DriverManager.getConnection(jdbcUrl, user, password) //獲取數(shù)據(jù)庫連接 Connection connection = DriverManager .getConnection(jdbcUrl, user, password); System.out.println(connection); }}總復(fù)習(xí)(包括獲取與數(shù)據(jù)庫的連接Connection,然后創(chuàng)建Statement,最后得到結(jié)果集ResultSet)
jdbc.properties文件內(nèi)容:
user=rootpassword=123driverClass=com.mysql.jdbc.DriverjdbcUrl=jdbc:mysql://localhost:3306/test
#user=scott#password=tiger#driverClass=oracle.jdbc.driver.OracleDriver#jdbcUrl=jdbc:oracle:thin:@127.0.0.1:1521:orcl
吾時而躬身自省,自省使知已之不足,知不足而奮起,未為晚也!
新聞熱點
疑難解答