Java Database Connectivity

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Assignment Name: Java Database Connectivity .

There are 5 steps to connect any java application with the database using JDBC. These steps are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection

1) Register the driver class


The forName() method of Class class is used to register the driver class. This method is used to dynamically
load the driver class.

Syntax of forName() method:


1. public static void forName(String className)throws ClassNotFoundException
2.
2) Create the connection object
The getConnection() method of DriverManager class is used to establish connection with the database.

Syntax of getConnection() method:


1. 1) public static Connection getConnection(String url)throws SQLException
2. 2) public static Connection getConnection(String url,String name,String password)
3. throws SQLException
4.
3) Create the Statement object
The createStatement() method of Connection interface is used to create statement. The object of statement
is responsible to execute queries with the database.

Syntax of createStatement() method:


1. public Statement createStatement()throws SQLException

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the database. This method
returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method:


1. public ResultSet executeQuery(String sql)throws SQLException

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically. The close() method of
Connection interface is used to close the connection.

Syntax of close() method:


1. public void close()throws SQLException
2.
Name: Create a Database using JDBC application.

Required Steps:

The following steps are required to create a new Database using JDBC application −

 Import the packages − Requires that you include the packages containing the JDBC classes needed for
database programming. Most often, using import java.sql.* will suffice.
 Open a connection − Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with the database server.
To create a new database, you need not give any database name while preparing database URL as
mentioned in the below example.
 Execute a query − Requires using an object of type Statement for building and submitting an SQL
statement to the database.
 Clean up the environment . try with resources automatically closes the resources.

Code :

package jdbc;
import java.sql.*;

public class create_database {

static final String DB_URL = "jdbc:mysql://localhost:3306/?characterEncoding=utf8";


static final String USER = "subarna";
static final String PASS = "123456";

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


Class.forName("com.mysql.jdbc.Driver");
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
) {
String sql = "CREATE DATABASE students";
stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Output:
Name: Select a Database using JDBC application.

Required Steps

The following steps are required to create a new Database using JDBC application −

 Import the packages − Requires that you include the packages containing the JDBC classes needed for
the database programming. Most often, using import java.sql.* will suffice.
 Open a connection − Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with a selected database.
Selection of database is made while you prepare database URL. Following example would make
connection with STUDENTS database.
 Clean up the environment − try with resources automatically closes the resources.

Code :

package jdbc;
import java.sql.*;

public class open_connection {

static final String DB_URL = "jdbc:mysql://localhost:3306/STUDENTS?characterEncoding=utf8";


static final String USER = "subarna";
static final String PASS = "123456";

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


Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);) {
System.out.println("Connected database successfully...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Output:
Name: Create a table using JDBC application.
Required Steps:
The following steps are required to create a new Database using JDBC application −
 Import the packages − Requires that you include the packages containing the JDBC classes needed for
database programming. Most often, using import java.sql.* will suffice.
 Open a connection − Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with a database server.
 Execute a query − Requires using an object of type Statement for building and submitting an SQL
statement to create a table in a seleted database.
 Clean up the environment − try with resources automatically closes the resources.
Code :
package jdbc;
import java.sql.*;

public class create_table {

final static String URL = "jdbc:mysql://localhost:3306/student?characterEncoding=utf8";


final static String USER = "subarna";
final static String PASSWORD = "123456";

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


Class.forName("com.mysql.jdbc.Driver");
try(Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Statement stmt = conn.createStatement();
) {
String sql = "CREATE TABLE REGISTRATION " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";

stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} catch (SQLException e) {
e.printStackTrace();
}

}
}

Output:
Name: Insert records in a table using JDBC application

Required Steps:

The following steps are required to create a new Database using JDBC application −

 Import the packages − Requires that you include the packages containing the JDBC classes needed for
database programming. Most often, using import java.sql.* will suffice.
 Register the JDBC driver − Requires that you initialize a driver so you can open a communications
channel with the database.
 Open a connection − Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with a database server.
 Execute a query − Requires using an object of type Statement for building and submitting an SQL
statement to insert records into a table.
 Clean up the environment try with resources automatically closes the resources.

Code :
package jdbc;
import java.sql.*;
public class insert {
final static String URL = "jdbc:mysql://localhost:3306/student?characterEncoding=utf8";
final static String USER = "subarna";
final static String PASSWORD = "123456";

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


Class.forName("com.mysql.jdbc.Driver");
try(Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Statement stmt = conn.createStatement();
) {
System.out.println("Inserting records into the table...");
String sql = "INSERT INTO Registration VALUES (1, 'Subarna', 'Acharjee', 20)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES (2, 'Mahnaz', 'Fatma', 25)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES (3, 'Zaid', 'Khan', 30)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES(4, 'Sumit', 'Mittal', 28)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");

} catch (SQLException e) {
e.printStackTrace();
}
}
}
Output:
Name: Select/ fetch records from a table using JDBC application

Required Steps

The following steps are required to create a new Database using JDBC application −

 Import the packages − Requires that you include the packages containing the JDBC classes needed for
database programming. Most often, using import java.sql.* will suffice.
 Open a connection − Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with a database server.
 Execute a query − Requires using an object of type Statement for building and submitting an SQL
statement to select (i.e. fetch ) records from a table.
 Extract Data − Once SQL query is executed, you can fetch records from the table.
 Clean up the environment − try with resources automatically closes the resources.

Code :

package jdbc;

import java.sql.*;
public class select {
final static String URL = "jdbc:mysql://localhost:3306/student?characterEncoding=utf8";
final static String USER = "subarna";
final static String PASSWORD = "123456";
static final String QUERY = "SELECT id, first, last, age FROM Registration";
public static void main(String[] args) throws ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
try(Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(QUERY);
) {
while(rs.next()){
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}

} catch (SQLException e) {
e.printStackTrace();
}
}
}

Output:
Name: Update records in a table using JDBC application.

Required Steps:
The following steps are required to create a new Database using JDBC application −
 Import the packages − Requires that you include the packages containing the JDBC classes needed for
database programming. Most often, using import java.sql.* will suffice.
 Open a connection − Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with a database server.
 Execute a query − Requires using an object of type Statement for building and submitting an SQL
statement to update records in a table. This Query makes use of IN and WHERE clause to update
conditional records.
 Clean up the environment − try with resources automatically closes the resources.

Code:
package jdbc;
import java.sql.*;
public class update {
final static String URL = "jdbc:mysql://localhost:3306/student?characterEncoding=utf8";
final static String USER = "subarna";
final static String PASSWORD = "123456";
static final String QUERY = "SELECT id, first, last, age FROM Registration";
public static void main(String[] args) throws ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
try(Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Statement stmt = conn.createStatement();
) {
String sql = "UPDATE Registration " +
"SET age = 19 WHERE id =1";
stmt.executeUpdate(sql);
ResultSet rs = stmt.executeQuery(QUERY);
while(rs.next()){
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
rs.close();

} catch (SQLException e) {
e.printStackTrace();
}
}
}
Output:

Before update After update


Name: Delete records from a table using JDBC application.

Required Steps

The following steps are required to create a new Database using JDBC application −

 Import the packages − Requires that you include the packages containing the JDBC classes needed for
database programming. Most often, using import java.sql.* will suffice.
 Register the JDBC driver − Requires that you initialize a driver so you can open a communications
channel with the database.
 Open a connection − Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with a database server.
 Execute a query − Requires using an object of type Statement for building and submitting an SQL
statement to delete records from a table. This Query makes use of the WHERE clause to delete
conditional records.
 Clean up the environment − try with resources automatically closes the resources.

Code :
package jdbc;
import java.sql.*;
public class delete {
final static String URL = "jdbc:mysql://localhost:3306/student?characterEncoding=utf8";
final static String USER = "subarna";
final static String PASSWORD = "123456";
static final String QUERY = "SELECT id, first, last, age FROM Registration";

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


Class.forName("com.mysql.jdbc.Driver");
try(Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Statement stmt = conn.createStatement();
) {
String sql = "DELETE FROM Registration " +
"WHERE id = 4";
stmt.executeUpdate(sql);
ResultSet rs = stmt.executeQuery(QUERY);
while(rs.next()){
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
rs.close();

} catch (SQLException e) {
e.printStackTrace();
}
}
}
Output:
Name: Delete a table using JDBC application.

Required Steps

The following steps are required to create a new Database using JDBC application −

 Import the packages − Requires that you include the packages containing the JDBC classes needed for
database programming. Most often, using import java.sql.* will suffice.
 Open a connection − Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with a database server.
 Execute a queryReformatting JDBC Tutorial Requires using an object of type Statement for building
and submitting an SQL statement to drop a table in a seleted database.
 Clean up the environment Reformatting JDBC Tutorial try with resources automatically closes the
resources.
Code :
package jdbc;
import java.sql.*;
public class drop_table {
final static String URL = "jdbc:mysql://localhost:3306/student?characterEncoding=utf8";
final static String USER = "subarna";
final static String PASSWORD = "123456";

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


Class.forName("com.mysql.jdbc.Driver");
try(Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Statement stmt = conn.createStatement();
) {
String sql = "DROP TABLE REGISTRATION";
stmt.executeUpdate(sql);
System.out.println("Table deleted in given database...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Output:
Name: Drop an existing Database using JDBC application.

Required Steps

The following steps are required to create a new Database using JDBC application −

 Import the packages − Requires that you include the packages containing the JDBC classes needed for
database programming. Most often, using import java.sql.* will suffice.
 Open a connection − Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with a database server.
Deleting a database does not require database name to be in your database URL. Following example
would delete STUDENTS database.
 Execute a query − Requires using an object of type Statement for building and submitting an SQL
statement to delete the database.
 Clean up the environment − try with resources automatically closes the resources.

Code :
package jdbc;
import java.sql.*;
public class drop_databasse {

static final String DB_URL = "jdbc:mysql://localhost:3306/STUDENTS?characterEncoding=utf8";


static final String USER = "subarna";
static final String PASS = "123456";
public static void main(String[] args) throws ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();) {
String sql = "DROP DATABASE STUDENTS";
stmt.executeUpdate(sql);
System.out.println("Database dropped successfully...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Output:

You might also like