How to connect to Oracle database from Java Program using JDBC API is common need for many Java programmer, though there are lot of framework available which has simplified JDBC development e.g hibernate, Spring JdbcTempate and many more, but creating Java program to connect to oracle database from plain old Java is still most easy and quickest method for testing and debugging database connectivity. Database connection program is also a common Java programming exercise in many Java programming courses on school, colleges and various training institutes. We have been exploring some advanced concepts and best practices on JDBC in my previous articles like Why should you use PreparedStatement in Java and 4 JDBC performance tips for Java application , which you may like if you are on more advanced level. This simple java program is intended for beginners in Java which have just started learning JDBC API.
If you like to read tutorials on database then you may find difference between truncate and delete , 10 example of SQL SELECT queries and how to manage database transaction useful and interesting.
How to connect Oracle Database from Java Program using JDBC - code example
Here is a complete code example of Java program to connect Oracle database using JDBC. This Java program will connect to Oracle database and print current date from "dual" system table. By the way before running this Java program to connect Oracle database make sure your Oracle database server is running and you have JDBC thin driver in your classpath like ojdbc6.jar or ojdbc6_g.jar.
Error and Exception while connecting Oracle Database from Java Program:
1) Invalid Username and Password
Exception in thread "main" java.sql.SQLException: ORA-01017: invalid username/password; logon denied
This Error comes when username and password provided to Java program connecting to Oracle database is not correct.
2)No suitable driver found
Exception in thread "main" java.sql.SQLException: No suitable driver found for
This Error comes when JDBC thin driver for relevant Oracle version is not in Classpath. e.g. ojdbc6.jar or ojdbc6_g.jar (compiled with javac -g with debug information) for Oracle 11g.
Also while reading data from ensure that you are using proper column index to avoid
In this Java program Example we have seen how to connect to Oracle database using JDBC thin driver , with thin driver its much easier to connect to oracle database as you don’t need to create data-sources like you do if you use JDBC ODBC Driver. Let me know if you face any issue while connecting to Oracle database form Java Program. Another worth noting point is connecting Oracle database using SSL from Java Program, which may see in another java tutorial.
Other Java Programming tutorial you may like