Introduction JDBC

23
1 Lecture Notes of Java Java Database Connectivity (JDBC)

description

Introduction

Transcript of Introduction JDBC

  • 1

    Lecture Notes of Java

    Java Database Connectivity (JDBC)

  • 2

    Java Database Connectivity (JDBC) Tutorial

    To use JDBC API, you can use interfaces and classes for writing

    database applications in java through making connection to databases.

    SQL, PL/SQL statements can send to any relational database by using

    JDBC API.

    JDBC is a Java API for executing SQL statements and supports basic

    SQL functionality.

    Moreover, as Java can run on a thin client, applets embedded in Web

    pages can contain downloadable JDBC code to enable remote database

    access.

    You will learn how to create a table, insert values into it, query the

    table, retrieve results, and update the table with the help of a JDBC

    Program example.

    Although, JDBC was designed specifically to provide a Java interface to

    relational databases, you may find that you need to write Java code to

    access non-relational databases as well.

    JDBC Architecture

    Java application calls the JDBC library. JDBC loads a driver which talks

    to the database. We can change database engines without changing

    database code.

  • 3

    Steps for Database Connectivity

    Before you can create a java jdbc connection to the database, you

    must first import the java.sql package.

    import java.sql.*;

    The star ( * ) indicates that all of the classes in the package java.sql

    are to be imported.

    Step 1: Loading a database driver

    In the first step, the jdbc connection process and we need to load the

    driver class by calling Class.forName() with the Driver class name as

    an argument.

    Once it loaded, the Driver class creates an instance of itself. A client

    can connect to Database Server through JDBC Driver.

    Since most of the Database servers support ODBC (Open database

    connectivity) driver therefore JDBC-ODBC Bridge driver is commonly

    used.

    The return type of the Class.forName (String ClassName) method is

    Class. Class is a class in java.lang package. For example,

    try {

    Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);

    //Or any other driver

    }

    catch(Exception x){

    System.out.println( Unable to load the driver class!

    );

    }

    Note: You can use ODBC Driver to connect with MS-Access, SQL

    Server, Dbase and Foxpro. In order to do this, you need to define first

    ODBC name through ODBC Data source control, which is present in

    control panel.

  • 4

    JDBC URL Syntax: jdbc: :

    JDBC URL Example: jdbc: :

    Each driver has its own subprotocol

    Each subprotocol has its own syntax for the source. Were using the

    jdbc odbc subprotocol, so the DriverManager knows to use the

    sun.jdbc.odbc.JdbcOdbcDriver.

    Step 2: Define Connection through DriverManager class

    The JDBC DriverManager class defines objects which can connect Java

    applications to a JDBC driver. DriverManager is considered the

    backbone of JDBC architecture.

    DriverManager class manages the JDBC drivers that are installed on

    the system. Its getConnection() method is used to establish a

    connection to a database.

    It uses a username, password, and a jdbc url to establish a connection

    to the database and returns a connection object.

    A jdbc Connection represents a session/connection with a specific

    database. Within the context of a Connection, SQL, PL/SQL statements

    are executed and results are returned.

    An application can have one or more connections with a single

    database, or it can have many connections with different databases.

    A Connection object provides metadata i.e. information about the

    database, tables, and fields. It also contains methods to deal with

    transactions.

  • 5

    Database Connectivity with username and password Example:

    String url= jdbc:odbc:ODBCName;

    try{

    Connection

    dbConnection=DriverManager.getConnection(url,loginName,Password);

    }

    catch( SQLException x ){

    System.out.println( Couldnt get connection! );

    }

    Database Connectivity without username and password

    Example:

    String url= jdbc:odbc:ODBCName;

    try{

    Connection dbConnection=DriverManager.getConnection(url);

    }

    catch( SQLException x ){

    System.out.println( Couldnt get connection! );

    }

    Step 3: Initiate SQL Statement

    Once a connection is obtained we can interact with the database.

    Connection interface defines methods for interacting with the database

    via the established connection.

    To execute SQL statements, you need to instantiate a Statement

    object from your connection object by using the createStatement()

    method. Syntax is given as:

    Statement statement = dbConnection.createStatement();

    A statement object is used to send and execute SQL statements to a

    database. There are following three kinds of Statements:

  • 6

    Statement: Execute simple sql queries without parameters.

    Statement createStatement()

    Creates an SQL Statement object.

    Prepared Statement: Execute precompiled sql queries with or

    without parameters.

    PreparedStatement prepareStatement(String sql)

    returns a new PreparedStatement object. PreparedStatement objects

    are precompiled SQL statements.

    Callable Statement: Execute a call to a database stored procedure.

    CallableStatement prepareCall(String sql)

    returns a new CallableStatement object. CallableStatement objects are

    SQL stored procedure call statements.

    Step 4: Execute SQL statement

    Statement interface defines methods that are used to interact with

    database via the execution of SQL statements. The Statement class

    has three methods for executing statements:

    executeQuery(), executeUpdate(), and execute().

    For a SELECT statement, the method to use is executeQuery.

    For statements that create or modify tables, the method to use is

    executeUpdate.

    Note: Statements that create a table, alter a table, or drop a table are

    all examples of DDL (Data definition language) statements and are

    executed with the method executeUpdate.

    execute() executes an SQL statement that is written as String object.

    For demonstration of all four steps, consider a simple example to

    display all records of faculty (faculty_code,faculty_name,designation)

    table from university database, which has odbc name as university.

  • 7

    import java.sql.*;

    public class JDBCDemo {

    public static void main( String[] args ) {

    try {

    // Connect to the database

    Class.forName("jdbc.odbc.JdbcOdbcDriver");

    String url = "jdbc:odbc:university";

    Connection con = DriverManager.getConnection(url);

    // Execute the SQL statement

    Statement stmt = con.createStatement();

    ResultSet resultSet = stmt.executeQuery("SELECT * from Faculty");

    System.out.println("Faculty Code Name Designation!");

    // Loop thru all the rows

    while( resultSet.next() ) {

    String code = resultSet.getString( "Faculty_code" );

    System.out.print( code );

    String name = resultSet.getString( "Faculty_Name" );

    System.out.print( name );

    String desg = resultSet.getString( "Designation" );

    System.out.println( desg );

    }

    stmt.close();

    }

    catch( Exception e ) {

    System.out.println(e.getMessage());

    e.printStackTrace();

    }

    }

    }

    This program provides access to a table of data generated by

    executing a Statement. The table rows are retrieved in sequence. A

    ResultSet maintains a cursor pointing to its current row of data. The

    next() method is used to successively step through the rows of the

    tabular results.

    Information: Please find this program in a file name JDBCDemo.java.

  • 8

    Connecting to a MySQL Database in Java

    In this section, you will learn how to connect the MySQL database with

    the Java file. Firstly, we need to establish a connection between

    MySQL and Java files with the help of MySQL driver.

    Now we will make our account in MySQL database so that we can get

    connected to the database. After establishing a connection, we can

    access or retrieve data form MySQL database. We are going to make a

    program on connecting to a MySQL database, after going through this

    program you will be able to establish a connection on your own PC.

    Information: Please find this program in a file name MysqlConnect.java.

    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 display a message "Disconnected from

    database".

    A short description is given below:

    String url = "jdbc:mysql://localhost:3306/";

    String dbName = "jdbctutorial";

    String driver = "com.mysql.jdbc.Driver";

    String userName = "root";

    String password = "root";

    try{

    Connection

    dbConnection=DriverManager.getConnection(url+dbName,username,Password);

    }

    catch( SQLException x ){

    System.out.println( Couldnt get connection! );

    }

  • 9

    Mapping MySQL Data Types in Java

    The following table represents the default Java mapping for various

    common MySQL data types:

    MySQL Type Java Type MySQL Type Java Type

    CHAR String FLOAT Double

    VARCHAR String DOUBLE Double

    LONGVARCHAR String BINARY byte []

    NUMERIC java.math.BigDecimal VARBINARY byte []

    DECIMAL java.math.BigDecimal LONGVARBINARY byte []

    BIT boolean DATE java.sql.Date

    TINYINT byte TIME java.sql.Time

    SMALLINT short TIMESTAMP java.sql.Tiimestamp

    INTEGER int BIGINT Long

    BIGINT long

    REAL float

    Creating a Database in MySQL

    After establishing the connection withMySQL database by using

    the JDBC driver, you will learn how we can create our database. A

    database is a large collection of data or information stored in our

    computer in an arranged way. It helps us for accessing, managing and

    updating the data easily. In this example we are going to create a

    database by MySQL and with the help of some java methods

    and SQL statement. A RDBMS (Relational Database Management

    System) is a type of DBMS (Database Management System) which

  • 10

    stores the data in the form of tables. So, we can view and use the

    same database in many different ways.

    Information: Please find this program in a file name

    CreateDatabase.java.

    Description of program:

    Firstly this program establishes the connection with MySQL database

    and takes a database name as its input in the database query and only

    after that it will create a new database and show a message "1 row(s)

    affected" otherwise, it displays "SQL statement is not executed!".

    Description of code:

    CREATE DATABASE db_name;

    Above code is used for creating a new database. It takes a database

    name and then a new database is created by that name.

    Creating a Database Table

    Table: A table is basic component of database (DB) that has number of

    rows and columns. All tables are stored in a specific database.

    Here we are providing you an example with code and it's description

    that helps you to create a database table by using java file. Brief

    description given below:

    Information: Please find this program in a file name CreatTable.java.

    Description of program:

    Firstly in this program we are going to establish the connection with

    database and creating a table with some fields. If table name already

    exists then we are displaying the message "Table already exists!".

  • 11

    Description of code:

    Statement:

    It is a interface. Statement object executes the SQL statement and

    returns the result it produces.

    createStatement():

    It is a method of Connection interface, which returns Statement object.

    This method will compile again and again whenever the program runs.

    CREATE TABLE table_name(field_name):

    An appropriate code used for creating a table with given field name.

    executeUpdate(String table):

    This method also executes SQL statement that may

    be INSERT, UPDATE OR DELETE statement are used in the code. It

    takes string types parameters for SQL statement. It returns int.

    Deleting a Table from Database

    Imagine a situation where we need to delete a table from the

    database. We can do it very easily by using the commands in the

    MySQL database. But, how we can delete the table using java methods

    and API. In this section we are describing, how to delete a table from

    database using java methods. Java provides the facility for deleting a

    specific table from a given database with the help of some specified

    methods. See detailed information given below:

    Information: Please find this program in a file name DeleteTable.java.

    Description of program:

    Create a class DeleteTable inside which, firstly establishes the

    connection with MySQL database. After establishing the connection we

    will delete a table from specific database. If the table which we want to

  • 12

    delete get deletes then we will print the message "Table Deletion

    process is completely successfully!", otherwise it will display " Table is

    not exists!".

    DROP TABLE table_name:

    Above code is used for deleting any table from a given database.

    Retrieving Tables from a Database

    In database system it is very important to know about the tables. To

    work with this, it is very important to know how to retrieve a table and

    create a table in the database. This section provides you a facility for

    retrieving tables from a specific database through an example. In

    relational database, all the data is stored in the tabular format (rows

    and columns). See detail information below:

    Information: Please find this program in a file name AllTableName.java.

    Description of program:

    In this program we are establishing the connection between

    the MySQL database and Java file. We will retrieve the table with the

    help of some java methods and APIs interface. If the database has one

    or more tables then it shows all tables, otherwise displays the

    message "No any table in the database".

    DatabaseMetaData:

    This is an interface of java.sql package that implemented by driver

    vendors. It tells about the data of the data like number of tables in the

    database, the information about the columns of the table.

    getMetaData():

    It is a method of Connection interface. This method has metadata

    around the database and retrieves DatabaseMetaData object.

    ResultSet:

    The ResultSet is an interface that provides getter methods

  • 13

    (getBoolean, getString, getTable and so on) for retrieving values.

    A ResultSet object is by default not updatable and forward only.

    getTables(null, null, "%", types):

    This method returns ResultSet and takes the following string types

    parameter:

    catalog : Table catalog name (may be null)

    schemaPattern : Table catalog name (may be null)

    tableNamePattern : Table name("%")

    types : Table type

    rs.next():

    This method returns the next element of the ResultSet object.

    getString("Table name"):

    Above method retrieves the values from ResultSet object. It takes

    string type value.

    Inserting values in MySQL database table

    After making the table in the database, we need to insert the values in

    the database. Here we are going to see, how we can insert values in

    the MySQL database table. We know that tables store data in rows and

    column format. After creating a database table, you need to insert the

    values in it. In this section, we are providing an example with code

    that provides the facility for inserting the values in MySQL database

    table.

    Description of program:

    First of all this program establishes the connection with MySQL

    database through the JDBC driver, after only that we will be able to

    insert the values in specific table with the help of some APIs and

    methods. If any values get inserted in the table then shows a message

  • 14

    "1 row affected" but if any problems comes while inserting the data in

    the table then it will displays the message "SQL statement is not

    executed!".

    Information: Please find this program in a file name

    InsertValues.java.

    INSERT table_name VALUES(field_values):

    Above code is used, when you want to insert values in the database

    table with appropriate value.

    Retrieving All Rows from a Database Table

    Here, you will learn how to retrieve all rows from a database table.

    You know that table contains the data in rows and columns format. If

    you want to access the data from a table then you need to use

    some APIs and methods. See brief descriptions for retrieving all rows

    from a database table as below:

    Information: Please find this program in a file name

    GetAllRows.java.

    Description of program:

    Program establishes the connection between MySQL database and java

    file so that we can retrieve all data from a specific database table. If

    any exception occurs then shows a message "SQL code does not

    execute.".

    executeQuery(String sql):

  • 15

    This method executes the SQL statement and returns a

    single ResultSet object. It takes string type parameter for executing

    the SQL statement.

    SELECT * FROM table_name:

    Above code retrieves all data from specific database table.

    getInt(String column_name):

    This method is of java.sql.ResultSet interface that takes string type

    parameter and returns an integer type values.

    getString(String column_name):

    This method is same as getInt() method but it returns the string type

    values.

    Count Rows from a Database Table

    After creating a database table, if we want to know number of rows in

    a table then we can get it very easily by using the simple database

    query. See brief description below:

    Information: Please find this program in a file name CountRows.java.

    Description of program:

    For this program to work firstly we need to establish the connection

    with MySQL database by the help of JDBC driver. When the connection

    has been established we need to pass a table name from the given

  • 16

    database in the query and the rows will be counted and the result will

    be displayed. If any exception is thrown then it will show "SQL

    statement is not executed!"

    Description of code:

    SELECT COUNT(*) FROM table_name;

    This code is used to count the rows of given table. table_name: It is a

    name of the table of which we want to see the rows.

    Getting Column Names from a database

    Here we are providing you an example with code that retrieves all

    columns name in a specific database table. Sometimes, you need to

    know the number of columns and the names of the columns of the

    table, so you can retrieve it with the help of this example. See detail

    information given below:

    Information: Please find this program in a file name

    Columename.java.

    Description of program:

    Create a class ColumnName. The name of the class should be such

    that the other person can easily understand what this program is going

    to do. Strictly follow the naming conventions of java. Now declare a

    static method inside which creates the connection

    with MySQL database through the JDBC driver. After establishing the

  • 17

    connection then you get all columns name and number of columns of

    specified table with the help of some APIs and methods.

    ResultSetMetaData:

    This is an interface of java.sql package that can be used for getting

    information about types and properties of columns in

    a ResultSet object.

    getColumnCount():

    Above method retrieves number of columns (integer types data) in

    the ResultSet object.

    getColumnName(int column):

    This method returns columns name (string type data)

    from ResultSetMetaData object and takes integer type value.

    Adding a New Column Name in Database Table

    In this jdbc tutorial program we are going to learn about adding a new

    column in database table. Sometimes it happens that we have created

    a table and forgets to add some important column name into it. Later

    while retrieving the data from that table we come to know that the

    table doesn't contains that particular column we are searching for. So

    there is no need to get panic. We have the solution for this, we are

    describing it with the help of the simple example. Brief description

    given below:

    Description of program:

  • 18

    Firstly we need to create a connection with the help of JDBC driver for

    connecting to the MySQLdatabase. Remember, in this program we are

    going to add columns to an existing database table. After establishing

    the connection, it takes table name, column name and it's data type

    and at last add a new column in the table. If the column gets inserted

    or added in the table then it shows "Query OK, n rows affected"

    otherwise it will displays a message "Table or column or data type is

    not found!".

    Information: Please find this program in a file name

    AddColume.java.

    ALTER TABLE table_name ADD col_name data_type;

    Above code is used for adding a new column in the database table and

    takes appropriate attributes:

    table_name: This is a table name in which you want to add a new

    column name.

    col_name: It is a name of the column that you want to add in a table.

    data_type: This is a data type of new column.

    Sum of Column in a Database Table

    This section describes how we can calculate the sum of specific column

    data in the database table. Consider an example of any university

    where we need to calculate the sum of numbers achieved by the

    student. Either we can do it manually or by using just the simple

  • 19

    query. By doing it manually is a very cumbersome work, but by using

    simple query it can be done very easily. By seeing the example given

    below you can easily understand how you can get the sum of specific

    column. Here we are providing you an example.

    Information: Please find this program in a file name

    SumColume.java.

    Description of program:

    In the program the first task we going to do is to establish the

    connection with MySQL database by using the JDBC driver. When the

    connection has been established pass the table name and name of that

    column of which we want to calculate the sum. If the statement gets

    processed then it shows the sum of the particular column else it will

    displays a message "SQL statement is not executed!".

    SELECT SUM(col_name) FROM table_name:

    This code can be used to calculate the sum of specific column in

    database table.

    Deleting All Rows from a Database Table

    Consider a case where we have been given one database table, now

    we have to delete all the rows from the table. This section describes

    for deleting all rows from a specific database table. Deleting all rows

    with the help of some java methods and APIs interfaces that is given

    below:

  • 20

    Information: Please find this program in a file name

    DeleteAllRows.java.

    Description of program:

    This program establishes the connection between the MySQL database

    and java file with the help of a jdbc driver. After that deletes all rows

    by the SQL statement and shows a message "All rows are completely

    deleted!". If SQL statement is not executed then displays "SQL

    statement is not executed!".

    Delete from table.

    Delete a Specific Row from a Database Table

    Consider a case where we are creating a table and we have to add

    some data in it. It may happen that we might add a wrong data in a

    row, now we need to delete that wrong data. This can be done very

    easily, and in this section we are going to do the same that is, how to

    delete a specific row from a specific database table. Here is an

    example with code which provides the facility for deleting specific row

    in a database table. Sometimes, you want to delete a specific row then

    you use some java methods and APIs interfaces. Detail information

    given below:

  • 21

    Information: Please find this program in a file name

    DeleteSpecificRow.java.

    Description of program:

    Firstly, in this program we are going to establish the connection by

    using MySQL database. After establishing the connection we are going

    to delete a specific row from the table. If the row get deletes

    successfully then it will shows an appropriate message: "Row is

    deleted.". If the row doesn't gets deleted then displays a message:

    "Row is not deleted". If there arises any problem while establishing the

    connection or there doesn't exist the table by that name or there is no

    data in the table then the exception will be thrown that "SQL

    statement is not executed". If any problems occurs while making

    connection then system displays a message with the help

    of java.lang.ClassNotFoundExceptionexception.

    Description of code:

    DELETE FROM employee6 WHERE Emp_code = '1':

    Above code deletes the record in the employee6 table which

    has Emp_code = '1'.

    employee6: This is a table name of a specific database.

    Emp_code: It specifies the column name of a specific database table.

    '1': This is the value of specified column name.

  • 22

    Join tables

    Consider a case, where there is too many records and tables in a

    database. Now to retrieve a particular row from a table or database is

    a very time consuming. So, what the alternative to that, divide the

    table in more than one table. In this section, we are going to see how

    to join two or more tables in a specific database. For this you need to

    have two or more table in the database. If two or more tables are

    available in the database then Join operation is performed otherwise

    not. Firstly, it is important to know about the join operation. Join

    operation provides the facility to combine records between two or

    more tables. It relates one table to another. Joining is the type of

    query for retrieving data two or more table in specific database. You

    can join the tables various types like: Natural join, Natural left join,

    Natural right join and so on. Here we are providing you an example

    with code that joins two tables through theNATURAL JOIN. Brief

    information given below:

    Join: A join provides the facility to connect two tables are merged to

    each other according to field that is common and creates a new virtual

    table.

    NATURAL JOIN: It is a type of join that retrieves data within specified

    tables to specific field is matched.

    NATURAL LEFT JOIN: In this operation both tables are merged to each

    other according to common fields but the priority is given to the first

    table in database.

  • 23

    NATURAL RIGHT JOIN: It also same as Natural left join but it retrieves

    the data from the second table in the database.

    Information: Please find this program in a file name

    NatJoinTable.java.

    Description of program:

    First of all, this program establishes the connection

    with MySQL database through the JDBC driver. After establishing the

    connection the NATURAL JOIN operation is performed within two tables

    say: employee and Emp_sal. The employee table holds the Emp_ed

    and Emp_name fields and Emp_sal table contains the Emp_name and

    Emp_sal. We are making use of the emp_name to join the tables.

    Description of code:

    SELECT *FROM employee NATURAL JOIN Emp_sal:

    This code is used to show all fields that matches in the both tables on

    the basis of Emp_name field.

    =========== End of JDBC=========================

    JDBC Architecture

    Steps for Database ConnectivityConnecting to a MySQL Database in JavaMapping MySQL Data Types in JavaCreating a Database in MySQLCreating a Database TableDeleting a Table from DatabaseRetrieving Tables from a DatabaseInserting values in MySQL database tableRetrieving All Rows from a Database TableCount Rows from a Database TableGetting Column Names from a databaseAdding a New Column Name in Database TableSum of Column in a Database TableDeleting All Rows from a Database TableDelete a Specific Row from a Database TableJoin tables