如何使用JDBC从Java连接到Oracle数据库?
要连接Oracle数据库,首先需添加Oracle JDBC驱动并建立连接,1. 添加ojdbc驱动:使用Maven时可配置Oracle仓库或手动安装ojdbc8.jar到本地仓库,非Maven项目则直接下载JAR并加入classpath;2. 建立连接:JDBC 4.0以上无需显式加载驱动,使用DriverManager.getConnection()配合正确URL格式,如jdbc:oracle:thin:@localhost:1521:ORCL(SID)或jdbc:oracle:thin:@//localhost:1521/ORCLPDB1(服务名),并在代码中通过try-with-resources安全执行SQL;3. 注意SID与服务名的URL差异,必要时支持TNS或SSL连接;4. 常见问题包括驱动未找到(检查classpath)、ORA-12505错误(核对SID/服务名)、连接超时(确认监听和端口)以及Java版本兼容性(Java 8-17用ojdbc8)。正确配置后,标准JDBC操作即可正常运行,且应始终妥善处理SQLException。
Connecting to an Oracle database from Java using JDBC involves a few key steps: loading the driver, establishing a connection, and then working with SQL statements. Here's a straightforward guide to get you up and running.

1. Add the Oracle JDBC Driver (ojdbc)
Oracle’s JDBC driver is not in Maven Central by default due to licensing, but you can still include it in your project.
If using Maven:
You can manually install the ojdbc8.jar
(for Java 8 ) into your local repository or use a repository that hosts it (like Oracle’s Maven repository after registration).

Alternatively, if you’ve downloaded the JAR:
<dependency> <groupId>com.oracle.database.jdbc</groupId> <artifactId>ojdbc8</artifactId> <version>21.7.0.0</version> </dependency>
Note: You may need to configure Oracle’s Maven repository or install the JAR locally using
mvn install
.
Manual Setup:
If not using Maven, download the appropriate ojdbc
JAR from Oracle’s website, and add it to your classpath.
2. Load the JDBC Driver and Connect
Starting from JDBC 4.0 (Java 6 ), loading the driver manually (Class.forName
) is optional, but it's still sometimes used for clarity or older environments.
Connection URL Format:
jdbc:oracle:thin:@hostname:port:service_id -- or jdbc:oracle:thin:@//hostname:port/service_name
- Use
:
before SID (e.g.,:ORCL
) - Use
//
before service name (e.g.,/ORCLPDB1
)
Example Code:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.sql.ResultSet; public class OracleJDBCExample { public static void main(String[] args) { // Database connection parameters String url = "jdbc:oracle:thin:@localhost:1521:ORCL"; // or for service name: "jdbc:oracle:thin:@//localhost:1521/ORCLPDB1" String username = "your_username"; String password = "your_password"; try (Connection conn = DriverManager.getConnection(url, username, password); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT 'Hello from Oracle' FROM DUAL")) { while (rs.next()) { System.out.println(rs.getString(1)); } } catch (SQLException e) { e.printStackTrace(); } } }
3. Common Connection Scenarios
SID vs Service Name:
- If connecting via SID:
jdbc:oracle:thin:@host:port:SID
- If connecting via Service Name:
jdbc:oracle:thin:@//host:port/service_name
- If connecting via SID:
Using TNS Names (Advanced):
You can also use a TNS alias if configured:jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCLPDB1)))
SSL or Wallet Connections:
More complex setups (like Autonomous Database) may require additional parameters and Oracle Wallets.-
ClassNotFoundException: Make sure
ojdbc8.jar
(or similar) is in your classpath. - ORA-12505: SID not found: Double-check SID vs service name syntax.
- ORA-12170: Connection timeout: Verify Oracle is running, listener is up, and port 1521 is open.
-
Java Version Compatibility: Use
ojdbc8.jar
for Java 8–17,ojdbc11.jar
for Java 11 , etc.
4. Troubleshooting Tips
Basically, once the driver is in place and the connection string is correct, standard JDBC operations (queries, updates, etc.) work as expected. Just remember to handle SQLException
and use try-with-resources to manage connections safely.
以上是如何使用JDBC从Java连接到Oracle数据库?的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undress AI Tool
免费脱衣服图片

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Yes,AWRandADDMreportsareessentialforOracleperformancetuning.1.AWRreportsprovidesnapshotsofdatabaseactivity,showingtopSQL,waitevents,resourceusage,andtrendsovertime—usefulforidentifyinginefficientqueriesandcacheeffectiveness.2.ADDManalyzesAWRdatatodet

Oracle自动处理不同字符集之间的转换,但若目标字符集无法表示源字符集中的字符,则可能出现数据丢失或替换。其核心机制是使用内置转换引擎进行字符映射,常见于客户端与数据库NLS_LANG设置不一致、跨数据库传输或使用CONVERT()函数时。关键注意事项包括:1.使用AL32UTF8作为数据库字符集以支持Unicode;2.正确配置客户端NLS_LANG;3.使用NVARCHAR2和NCLOB存储多语言数据;4.迁移前用CSSCAN工具检测潜在问题;5.警惕LENGTH()、SUBSTR()等函

NLS\_LANG设置错误会导致数据乱码或格式错误,其包含语言、地区和字符集三要素,应确保客户端与数据库的字符集匹配,推荐使用AL32UTF8以支持Unicode,并通过ALTERSESSION控制会话级参数,同时在Unix/Linux中配置环境变量或Windows注册表以正确应用设置。具体要点包括:1.NLS\_LANG决定消息翻译、日期货币格式及字符编码转换;2.客户端字符集必须与数据库兼容,否则导致数据损坏;3.避免自动转换,需测试特殊字符;4.其他NLS参数如NLS\_DATE\_FOR

Storedprocedures,functions,andpackagesinPL/SQLimprovecodemodularityandreusabilitybyencapsulatinglogic,promotingcentralizedmaintenance,andorganizingrelatedcomponents.1.Storedprocedurescentralizebusinesslogicintocallableunits,reducingredundancyandsimpl

Oracle死锁发生在两个或多个会话相互等待对方释放资源锁时,形成循环依赖。例如:1.会话A更新行1后尝试更新行2;2.会话B更新行2后尝试更新行1,若同时运行则互相阻塞形成死锁。Oracle自动检测并回滚其中一个事务以打破死锁,该事务会收到ORA-00060错误。其他常见原因包括未提交事务持有行级锁、索引使用不当导致锁升级、应用程序逻辑允许无序重叠更新。检测方法包括查看警报日志中的死锁记录、追踪文件及查询V$LOCKED_OBJECT和V$SESSION视图。解决方式为分析追踪文件、确保事务一

OracleFlashbacktechnologyoffersmultiplerecoveryoptionstoaddresslogicalerrorswithminimaldowntime.1.FlashbackDatabaseallowsrollingbacktheentiredatabaseusingflashbacklogsintherecoveryareatoaspecificpointintime.2.FlashbackTablerecoversindividualtablesaff

运行SELECT*FROMv$version;可获取Oracle数据库的完整版本信息,包括数据库、PL/SQL、核心库等版本详情,是DBA最常用的可靠方法;2.使用SELECTbannerFROMv$versionWHEREbannerLIKE'Oracle%';可仅显示Oracle数据库主版本信息;3.查询PRODUCT_COMPONENT_VERSION视图可获取各Oracle组件的版本;4.通过sqlplus-V命令可在不登录数据库的情况下查看客户端或服务器工具版本,但可能不反映实际运行实

BULKCOLLECT和FORALL通过减少上下文切换显着提升PL/SQL性能。 1.BULKCOLLECT一次性批量获取多行数据到集合,避免逐行获取带来的频繁切换;2.FORALL将对集合的DML操作一次性发送至SQL引擎处理,取代低效的循环逐条执行;3.二者结合可实现高效的数据提取、处理与更新,适用于ETL、批量任务等场景;4.使用时需注意控制集合大小、合理使用LIMIT分批处理,并避免在FORALL中加入复杂条件逻辑。
