Java J2ee Tutorials

MySQL Database Connection in Java

Monday, January 23, 2012

Description of program:

This program establishes the connection between MySQL database and java files with the help of various types of APIs interfaces and methods. If connection is established then it shows "Connected to the database" otherwise it will displays a message "Disconnected from database".

Description of 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.

Code of program:

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 = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
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();
}
}
}

Free Career Predictions

0 comments:

Post a Comment