1,查詢數據庫的7個標準步驟java
1)載入JDBC驅動程序數據庫
只須要在Class.forName方法中指定數據庫驅動程序類名。服務器
try { Class.forName("connect.microsoft.MicrosoftDriver"); Class.forName("oracle.jdbc.driver.OracleDriver"); Class.forName("com.sybase.jdbc.SybDriver"); } catch(ClassNotFoundException cnfe) { System.err.println("Error loading driver: " + cnfe); }
2)定義URLoracle
鏈接URL是指服務器的主機名,端口以及但願與之創建鏈接的數據庫名spa
String host = "dbhost.yourcompany.com"; String dbName = "someName"; int port = 1234; String oracleURL = "jdbc:oracle:thin:@" + host + ":" + port + ":" + dbName; String sybaseURL = "jdbc:sybase:Tds:" + host + ":" + port + ":" + "?SERVICENAME=" + dbName; String msAccessURL = "jdbc:odbc:" + dbName;
3)創建鏈接code
有了鏈接URL,用戶名,密碼,就能夠創建到數據庫對象
String username = "jay_debesee"; String password = "secret"; Connection connection = DriverManager.getConnection(oracleURL, username, password);
4)建立Statement對象get
建立Statement對象才能向數據庫發送查詢和命令io
Statement statement = connection.createStatement();
5)執行查詢或更新table
有了Statement對象後,就可使用execute,executeQuary,executeUpdate或executeBatch方法發送SQL語句到數據庫
String query = "SELECT col1, col2, col3 FROM sometable"; ResultSet resultSet = statement.executeQuery(query);
6)結果處理
數據庫查詢執行完畢後,返回一個ResultSet,ResultSet表示一系列的行和列,可使用next和各類getXxx方法來處理這些行和列
next/previous
getXxx
wasNull
findColumn
getRow 等方法
7)關閉鏈接
connection.close();