標籤:
JDBC(Java Data Base Connectivity,java資料庫連接)是一種用於執行SQL語句的Java API,可以為多種關聯式資料庫提供統一訪問,它由一組用Java語言編寫的類和介面組成。JDBC提供了一種基準,據此可以構建更進階的工具和介面,使資料庫開發人員能夠編寫資料庫應用程式。JDBC只向各大資料庫產商提供統一的驅動介面,具體的實現由各大產商實現,每個資料庫產商有不同的實現,但是我們可以利用多態,實現面向介面編程,而不用管資料庫產商的具體實現細節。在Java程式中使用具體資料庫時,需要先引入對應的jar包。比如mysql對應的mysql-connector-java-5.1.13-bin.jar,如果是oracle等資料庫需要引入其他的jar包。
JDBC建立串連(MySQL)
在類路徑下建立properties檔案,在工具類JDBCTools中載入該檔案
在jdbc.properties檔案中:
1 driverClass = com.mysql.jdbc.Driver //這一句代表資料庫驅動類的全類名2 jdbcUrl = jdbc:mysql://localhost:3306/test //這一句是配置需要訪問的資料庫,test是資料庫名3 user = root4 password = 123
建立資料庫連接和關閉串連的工具類jdbcTools
1 public class jdbcTools { 2 3 //擷取資料庫連接 4 public static Connection getConnection() throws Exception { 5 Connection connection = null; 6 String driverClass = null; 7 String url = null; 8 String user = null; 9 String password = null;10 11 InputStream in = jdbcTools.class.getClassLoader().getResourceAsStream("jdbc.properties");//載入設定檔12 Properties properties = new Properties();13 properties.load(in);14 15 driverClass = properties.getProperty("driverClass");16 url = properties.getProperty("jdbcUrl");17 user = properties.getProperty("user");18 password = properties.getProperty("password");19 20 Class.forName(driverClass);//通過全類名載入驅動類21 connection = DriverManager.getConnection(url,user,password);//DriverManager可以實現對各個資料庫驅動類的同一管理,並擷取資料庫的串連22 23 return connection;24 25 }26 27 //關閉資源28 public static void releaseResource(Statement statement,Connection connection){29 if(statement != null){30 try{31 statement.close();32 }catch (Exception e){33 e.printStackTrace();34 }35 }36 if(connection != null){37 try{38 connection.close();39 }catch (Exception e1){40 e1.printStackTrace();41 }42 }43 }44 45 public static void releaseResource(ResultSet resultSet,Statement statement, Connection connection){46 47 if(resultSet != null){48 try{49 resultSet.close();50 }catch (Exception e){51 e.printStackTrace();52 }53 }54 if(statement != null){55 try{56 statement.close();57 }catch (Exception e){58 e.printStackTrace();59 }60 }61 if(connection != null){62 try{63 connection.close();64 }catch (Exception e1){65 e1.printStackTrace();66 }67 }68 }
JDBC建立/關閉資料庫連接