通过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)+" "); } 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(); } } } }