Java中通过JDBC连接Oracle数据库
时间:2021-07-01 10:21:17
帮助过:19人阅读
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();
}
}
}
}
Java中通过JDBC连接Oracle数据库
标签: