With java you can easily connect java applications to a database in which you can store retrieve and manipulate data easily . Well to do this you must know the fundamentals of java programming as well as SQL as you might need to perform complex operations like retrieving data simultaneously and joining multiple tables at a single time.Anyways let us look learn how to connect and retrieve data from a MYSQL Database .
Following are the pre-coding steps you need to do :-
1:-Download the database driver jar file for mysql.
2:-Add the downloaded jar file to your main applications classpath . This is generally required to prevent CLASS NOT FOUND EXCEPTION thrown when you try to execute the Below line Class.forName(“com.mysql.jdbc.Driver”); -> This line would load the Database Driver jar class files if file is not found an Exception would be thrown .
3:-Once you’ve done with the above two steps .. Its time for us to write a code that will connect to the project_db Database .
Now look at the below code to gain knowledge on how to connect java to MYSQL database :-
import java.sql.*;
public class MysqlConnect{
public static void main(String[] args) {
System.out.println(“MySQL Connect Example.”);
Connection conn = null;
String url = “jdbc:mysql://localhost:3306/”;
String dbName = “project_db”;
String driver = “com.mysql.jdbc.Driver”;
String userName = “root”;
String password = “”;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println(“Connected to the database”);
conn.close();
System.out.println(“Disconnected from database”);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Description of the code:-
Connection:
This is an interface in java.sql package that specifies connection with specific database like: MySQL, Ms-Access, Oracle etc and java files. The SQL statements are executed within the context of the Connection interface.
Class.forName(String driver):
This method is static. It attempts to load the class and returns class instance and takes string type value (driver) after that matches class with given string.
DriverManager:
It is a class of java.sql package that controls a set of JDBC drivers. Each driver has to be register with this class.
getConnection(String url, String userName, String password):
This method establishes a connection to specified database url. It takes three string types of arguments like:
url : - Database url where stored or created your database
userName : - User name of MySQL
password : -Password of MySQL
con.close():
This method is used for disconnecting the connection. It frees all the resources occupied by the database.
printStackTrace():
The method is used to show error messages. If the connection is not established then exception is thrown and print the message.