Connecting to a MySQL Database in Java


Jul 24, 2011    Janaki Mahapatra, JAVA

Connection: This is an interface in  java.sql package that specifies connection with specific database like: MySQL,Ms-AccessOracle 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. Here is the 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();   }   } }