0% found this document useful (0 votes)
9 views3 pages

JDBC Connection

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views3 pages

JDBC Connection

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Java provides a library to be imported to build up a connection with an existing database in our local

machines. Let's move on..


Prerequisites :
JDK should be installed.
XAMMP or WAMP should be installed.
Netbeans is required.

Create a new JAVA project using Netbeans


Open Netbeans and go to File. Select add new project and create.

Import MYSQL JDBC Driver


There's a sub folder in your project called Libraries. Right click on it and select import library option.
Search for MYSQL JDBC Driver and click on it to import. The below demo will show you the way...

Create a new database


Open XAMMP/WAMP and start up the MYSQL service and APACHE service.
Then go to localhost/phpmyadmin and create a new database called javadb.

Or you can use SQL command to create this database.


Login to MYSQL command line using this command.
mysql -u root

If you have set a password, then use this command and then enter your password.
mysql -u root -p

Then use the below SQL command to create the database.


CREATE DATABASE javadb;

Get the code and replace


I have placed the code here. Copy it and paste in the newly created DatabaseJava class file.

package databasejava;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseJava {

public static void main(String[] args) throws SQLException {


try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException ex){
System.out.println("Driver not found");
}
try(
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/javadb","root","")) {
System.out.println("Connected Successfully");

}catch(SQLException ex){
System.out.println(ex.getMessage());
}
}
}

Here, for getConnection method you must you your database credentials correctly. In my case database
is javadb, user is default root, port is 3306 and password is empty. Exceptions are created to catch the
unexpected behaviors. Ex: If the Driver is not found or Connection is not created....

Run the project


Right click on project and select Run to run the project OR press F6 button. You will get an output like
this. It means the Database connection has been built!

Now you have established a new database connection successfully! So, this is not enough! We have to
do something using this database connection. Therefore my next articles will be based on JAVA CRUD
operations. Till then,

Good Bye!!!

You might also like