Oracle数据库操作:如何使用Java连接Oracle数据库并执行查询?
在Java中,我们可以使用JDBC(Java Database Connectivity)来连接Oracle数据库并执行查询。以下是一个基本的步骤:
添加依赖**
首先需要在你的项目pom.xml文件中添加Oracle和对应驱动的依赖。<dependencies>
<!-- Oracle JDBC driver -->
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc10</artifactId>
<version>19.3.0.0</version> <!-- Update the version according to availability -->
<scope>runtime</scope>
</dependency>
</dependencies>
建立连接**
使用JDBC的DriverManager.getConnection()
方法来获取数据库连接。import java.sql.Connection;
import java.sql.DriverManager;
public class OracleDatabaseConnection {
private static final String DATABASE_URL = "jdbc
thin:@//localhost:1521/XE";
public static Connection getConnection() throws Exception {
// Register the JDBC driver
Class.forName("com.oracle.database.jdbc.driver.OracleDriver");
// Open a connection
return DriverManager.getConnection(DATABASE_URL);
}
}
执行查询**
一旦连接成功,你可以使用Statement
或PreparedStatement
对象来执行SQL查询。Statement stmt = OracleDatabaseConnection.getConnection().createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM TABLE_NAME"); // Replace TABLE_NAME with your table name
while (rs.next()) {
// Access columns by index or column name
int column1Value = rs.getInt("COLUMN1_NAME"));
String column2Value = rs.getString("COLUMN2_NAME"));
System.out.println("Column 1 Value: " + column1Value);
System.out.println("Column 2 Value: " + column2Value);
}
stmt.close();
rs.close();
这样,你就可以在Java中连接Oracle数据库并执行查询了。
还没有评论,来说两句吧...