通過jdbc連接數據庫,攏共分三步:
第一步:下載一個JDBC的驅動,然后把jar包扔到項目里並add to build path;
第二步:去本地oracle文件夾下找到“TNSNAMES.ORA”文件,打開找到對應數據庫的連接字符串,作為jdbc的連接字符串;
第三步:寫代碼,通過jdbc連接數據庫。
從網上找了段代碼,做了下修改。以下為查詢數據庫表中所有字段及字段值類型,遍歷數據庫表中所有數據(其中xxx均為需要替換的信息):
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; public class ConnectDB { public static void main(String[] args) { connectDB(); } public static void connectDB() { Connection con = null; PreparedStatement pre = null; ResultSet results = null; ResultSetMetaData resultSetMetaData = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("開始嘗試連接數據庫!"); // 必須用oracle文件夾下"tnsnames.ora"配置文件中配置的連接字符串進行遠程連接數據庫 String url = "jdbc:oracle:" + "thin:@(DESCRIPTION =" + "(ADDRESS_LIST =" + "(ADDRESS = (PROTOCOL = TCP)(HOST = xxx)(PORT = xxx))" + ")" + "(CONNECT_DATA =" + "(SERVICE_NAME = xxx)" + ")" + ")"; String user = "xxx"; String password = "xxx"; con = DriverManager.getConnection(url, user, password); System.out.println("連接成功!"); String sql = "select * from xxx"; pre = con.prepareStatement(sql); System.out.println("開始執行SQL語句!"); results = pre.executeQuery(); resultSetMetaData = results.getMetaData(); int columnCount = resultSetMetaData.getColumnCount(); // 獲取數據庫表所有字段名及字段值類型 for (int i = 1; i <= columnCount; i++) { System.out.println(resultSetMetaData.getColumnName(i) + ":" + resultSetMetaData.getColumnTypeName(i)); } while (results.next()) { for (int i = 1; i <= columnCount; i++) { System.out.print(results.getString(i)+"\t\t"); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (results != null) results.close(); if (pre != null) pre.close(); if (con != null) con.close(); System.out.println("數據庫連接已關閉!"); } catch (Exception e) { e.printStackTrace(); } } } }