以下是一个示例代码,演示如何使用Java连接Oracle数据库并执行SQL查询:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class OracleExample {
public static void main(String[] args) {
// 设置数据库连接信息
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String username = "your_username";
String password = "your_password";
// 连接数据库
Connection connection = null;
try {
connection = DriverManager.getConnection(url, username, password);
System.out.println("成功连接到Oracle数据库");
// 创建Statement对象
Statement statement = connection.createStatement();
// 执行SQL查询
String sql = "SELECT * FROM your_table";
ResultSet resultSet = statement.executeQuery(sql);
// 处理查询结果
while (resultSet.next()) {
// 获取每行的数据
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
// 关闭结果集和Statement对象
resultSet.close();
statement.close();
} catch (SQLException e) {
System.out.println("连接到Oracle数据库时发生错误");
e.printStackTrace();
} finally {
// 关闭数据库连接
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
System.out.println("关闭Oracle数据库连接时发生错误");
e.printStackTrace();
}
}
}
}
}
使用上述代码示例,可以在Java中连接Oracle数据库并执行SQL查询。请确保将your_username
和your_password
替换为实际的数据库用户名和密码,并将your_table
替换为要查询的实际表名。