JDBC Connection
For creating a JDBC connection to the database, we need to do the following :
1) Depending on the database, determine which driver will be needed.
2) Download the corresponding driver jar file and add it in project libraries.
3) Use the DriverManager class and JDBC url to create the connection.
In this example, we will be creating a connection to MySQL database. So, let’s get the corresponding driver.
MySQL driver
We can download this from MySQL website and add in the project library.
If using Maven as the build tool, add the following dependency in pom.xml and it will load the MySQL driver jar.
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency>
Now, lets write the JDBC connection program.
Connection url
The connection url depends on the database type.
For the MySQL database we are using, the connecton url is :
jdbc:mysql://localhost:3306/TestDatabase
For Oracle, in stead of jdbc:mysql:, it will start with jdbc:oracle:thin:@
Here is a sample connection url for oracle database “orcl”:
jdbc:oracle:thin:@//myhost:1521/orcl
JDBC Connection program
Here is a program that shows getting a connection to MySQL datatabase.
package com.topjavatutorial.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ExampleJDBCConnection { public static void main(String[] args) { try { Connection conn = getConnection(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Connection getConnection() throws SQLException{ //Change the connection url specific to your database, driver String url ="jdbc:mysql://localhost:3306/DatabaseName"; String user = "userid";//add your db user id here String password = "password";//add your db password here Connection conn = DriverManager.getConnection(url, user, password); System.out.println("Successfully connected"); return conn; } }
Output
Successfully connected
If no valid connection can be obtained, a java.sql.SQLException is thrown. Check the error details to determine if you have entered the connection string or id/pwd incorrectly.
After a valid connection has been obtained by your application, it can be used to work with the database.
© 2016, www.topjavatutorial.com. All rights reserved. On republishing this post, you must provide link to original post
#