How to connect java application with Mysql

Every java application needs database system to store application data. To connect java application to a RDBMS vendor you need JBDC driver.

Java provides api for connecting application to a RDBMS called java.sql package.
java.sql package contains interfaces and classes.Each RDBMS vendor provides implementations of their own.

Here we’re going to connect MySQl RDBMS with our application.


package com.startwithjava;
//Step 1: import java.sql api
import java.sql.*;

public class JDBCExample {
// JDBC driver name and database URL
static final String DRIVER = "com.mysql.jdbc.Driver";
static final String URL = "jdbc:mysql://localhost/mydb";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
try{
//Step 2: Load driver class by class.forName() method
 Class.forName(DRIVER);

//Step 3: Open a connection
conn = DriverManager.getConnection(URL,USER,PASS);

//Step 4: Connection interface provides factory method for getting instance of Statement to execute query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM Employee";
//Step 5: Execute query by executeQuery() for SELECT query. It will return ResultSet object.
ResultSet rs = stmt.executeQuery(sql);

//STEP 6: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
double salary = rs.getInt("salary");
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");

//Display values
System.out.print("\n ID: " + id);
System.out.print("\t First Name: " + firstName);
System.out.print("\t Last Name: " + lastName);
System.out.print("\t Age: " + age);
System.out.print("\t Salary: " + salary);
}
//STEP 7: Close connection
conn.close();
}catch(Exception e){
System.out.println("Exception: "+e)
}
}
}

Leave a Reply