11 MySql JDBC

You might also like

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

MySql and JDBC

Introduction to database
A database is simply a structured collection of data. The data relates to each other by nature.
This is why we use the term relational database.

In the relational database, we model data using tables. A table contains columns and rows. It is
like a spreadsheet. A table may relate to anther table using a relationship e.g., one-to-one, one-
to-many relationship etc.

Because we deal with a large amount of data, we need a way to define the databases, tables,
etc., and process data more effectively. In addition, we want to turn the data into information.
And this is where SQL comes to play.

SQL – the language of database

SQL stands for Structured Query Language. SQL is the standardized language used to access
the database.

SQL contains three parts:

∑ Data definition language (DDL) contains statements that help you define the database and
its objects e.g., tables, views, triggers, stored procedures, etc.
∑ Data manipulation language (DML) contains statements that allow you to update and
query data.
∑ Data control language (DCL) allows you to grant the permissions to a user to access a
certain data in the database.

MySql
My is the daughter’s name of the MySQL’s co-founder, Monty Widenius. The name of MySQL
is the combination of My and SQL, MySQL.

MySQL is a database management system that allows you to manage relational databases. It is
open source software backed by Oracle.
IPSR Solutions Ltd www.ipsr.edu.in 1
MySql and JDBC

Creating Database

CREATE DATABASE [IF NOT EXISTS] database_name;

Displaying Databases

SHOW DATABASES; - displays all databases in the MySQL database server

Selecting a database to work with

USE database_name;

Creating Table

CREATE TABLE [IF NOT EXISTS] table_name( column_list );

To define a column for the table in the CREATE TABLE statement, you use the following
syntax:

column_name data_type[size] [NOT NULL|NULL] [DEFAULT value] [AUTO_INCREMENT]

The most important components of the syntax above are:

∑ The column_name specifies the name of the column. Each column has a specific data
type and the size e.g.,VARCHAR(255)
∑ The NOT NULL or NULL indicates that the column accepts NULL value or not.
∑ The DEFAULT value is used to specify the default value of the column.
∑ The AUTO_INCREMENT indicates that the value of the column is increased
automatically whenever a new row is inserted into the table. Each table has one and only
one AUTO_INCREMENT column.

If you want to set particular columns of the table as the primary key, you use the following
syntax: PRIMARY KEY (col1,col2,...)

Using MySQL ALTER TABLE To Change Table Structure

The ALTER TABLE statement allows you to add a column, drop a column, change the data
type of column, add primary key, rename table, and many more.
IPSR Solutions Ltd www.ipsr.edu.in 2
MySql and JDBC

ALTER TABLE table_name action1[,action2,…]

Add a new column into a table

ALTER TABLE table_name

ADD COLUMN column_name datatype

[AFTER column_name];

Drop a column from a table

ALTER TABLE tasks

DROP COLUMN column_name;

Rename/ change the data type of a column

ALTER TABLE table_name

CHANGE column_name new_name new_data_type

Add primary key to a column

ALTER TABLE table_name

ADD PRIMARY KEY(primary_key_column);

Drop primary key

ALTER TABLE table_name

DROP PRIMARY KEY(primary_key_column);

Rename a table

ALTER TABLE table_name

RENAME TO new_name;

Or

RENAME TABLE old_table_name TO new_table_name;

IPSR Solutions Ltd www.ipsr.edu.in 3


MySql and JDBC

TRUNCATE TABLE statement

The MySQL TRUNCATE TABLE statement allows you to delete all data in a table. Therefore,
in terms of functionality, The TRUNCATE TABLE statement is like a DELETE statement
without a WHERE clause. However, in some cases, the MySQL TRUNCATE TABLE
statement is more efficient than the DELETE statement.

TRUNCATE TABLE table_name;

SELECT statement

The SELECT statement allows you to get the data from tables or views. A table consists of
rows and columns like a spreadsheet. The result of the SELECT statement is called a result set
that is a list of rows, each consisting of the same number of columns.

SELECT
column_1, column_2, ...
FROM
table_1
[INNER | LEFT |RIGHT] JOIN table_2 ON conditions
WHERE
conditions
GROUP BY column_1
HAVING group_conditions
ORDER BY column_1
LIMIT offset, length;
The SELECT statement consists of several clauses as explained in the following list:
∑ SELECT followed by a list of comma-separated columns or an asterisk (*) to indicate
that you want to return all columns.
∑ FROM specifies the table or view where you want to query the data.
∑ JOIN gets data from other tables based on certain join conditions.
IPSR Solutions Ltd www.ipsr.edu.in 4
MySql and JDBC

∑ WHERE filters rows in the result set.


∑ GROUP BY groups a set of rows into groups and applies aggregate functions on each
group.
∑ HAVING filters group based on groups defined by GROUP BY clause.
∑ ORDER BY specifies a list of columns for sorting.
∑ LIMIT constrains the number of returned rows.
The SELECT and FROM clause are required in the statement. Other parts are optional.
DISTINCT clause
In order to remove duplicate rows, you use the DISTINCT clause in the SELECT statement.
SELECT DISTINCT
columns
FROM
table_name
WHERE
where_conditions;
Filter Rows Using MySQL WHERE
The WHERE clause allows you to specify exact rows to select based on a particular filtering
expression or condition.
Comparison operators such as <,>,<=,>=,!= and = can be used to form filtering expressions in
the WHERE clause.
There are also some useful operators that you can use in the WHERE clause to form complex
conditions such as:
∑ BETWEEN selects values within a range of values.
∑ LIKE matches value based on pattern matching.
∑ IN specifies if the value matches any value in a list.
∑ IS NULL checks if the value is NULL.
The WHERE clause is used not only with the SELECT statement but also other SQL statements
to filter rows such as DELETE and UPDATE.
IPSR Solutions Ltd www.ipsr.edu.in 5
MySql and JDBC

Querying Data with MySQL IN Operator


The IN operator allows you to determine if a specified value matches any one of a list or a
subquery.
SELECT
column1,column2,...
FROM
table_name
WHERE
(expr|column_1) IN ('value1','value2',...);
The IN operator can also be used in the WHERE clause of other statements such as INSERT,
UPDATE, DELETE, etc.
You can combine the IN operator with the NOT operator to determine if a value does not match
any value in a list or a subquery.
MySql BETWEEN operator
The BETWEEN operator allows you to specify a range to test. We often use the BETWEEN
operator in the WHERE clause of the SELECT, INSERT, UPDATE, and DELETE statements.
expr [NOT] BETWEEN begin_expr AND end_expr;
The expr is the expression to test in the range that is defined by begin_expr and end_expr.
All three expressions: expr, begin_expr, and end_expr must have the same data type.
The BETWEEN operator returns true if the value of the expr is greater than or equal to (>=) the
value of begin_expr and less than or equal to (<= ) the value of the end_expr otherwise it
returns zero.
Using MySQL LIKE operator to select data based on patterns
The LIKE operator is commonly used to select data based on patterns. Therefore, the LIKE
operator is often used in the WHERE clause of the SELECT statement.
MySQL provides two wildcard characters for using with the LIKE operator, the percentage %
and underscore _ .

IPSR Solutions Ltd www.ipsr.edu.in 6


MySql and JDBC

∑ The percentage ( % ) wildcard allows you to match any string of zero or more characters.
∑ The underscore ( _ ) wildcard allows you to match any single character.
The MySQL allows you to combine the NOT operator with the LIKE operator to find a string
that does not match a specific pattern.
Using LIMIT to Constrain The Number of Rows Returned By SELECT Statement
The LIMIT clause is used in the SELECT statement to constrain the number of rows in a result
set. The LIMIT clause accepts one or two arguments. The values of both arguments must be
zero or positive integers.
SELECT
column1,column2,...
FROM
table
LIMIT offset , count;
∑ The offset specifies the offset of the first row to return. The offset of the first row is 0, not 1.
∑ The count specifies the maximum number of rows to return.
When you use LIMIT with one argument, this argument will be used to specifies the maximum
number of rows to return from the beginning of the result set.
Using MySQL LIMIT to get the highest and lowest values
The LIMIT clause is often used with ORDER BY clause. First, you use the ORDER BY clause
to sort the result set based on certain criteria, and then you use the LIMIT clause to find lowest
or highest values.
Sorting Rows with MySQL ORDER BY
The ORDER BY clause allows you to:
∑ Sort a result set by a single column or multiple columns.
∑ Sort a result set by different columns in ascending or descending order.
SELECT column1, column2,...
FROM tbl
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC],...
IPSR Solutions Ltd www.ipsr.edu.in 7
MySql and JDBC

The ASC stands for ascending and the DESC stands for descending. By default, the ORDER
BY clause sorts the result set in ascending order if you don’t specify ASC or DESC explicitly.
Using MySQL Alias To Make The Queries More Readable
MySQL supports two kinds of aliases which are known as column alias and table alias.
MySQL alias for columns
Sometimes the names of columns are so technical that make the query’s output very difficult to
understand. To give a column a descriptive name, you use a column alias.
SELECT
[column_1 | expression] AS descriptive_name
FROM table_name;
To give a column an alias, you use the AS keyword followed by the alias. If the alias contains
space, you must quote it.
SELECT
CONCAT_WS(', ', lastName, firstname) AS `Full name`
FROM employees;
Because the AS keyword is optional, you can omit it in the statement. Note that you can also
give an expression an alias. In MySQL, you can use the column alias in the ORDER BY,
GROUP BY and HAVING clauses to refer to the column.
MySQL alias for tables
You can use an alias to give a table a different name. You assign a table an alias by using the
AS keyword as the following syntax:
table_name AS table_alias
You often use the table alias in the statement that contains INNER JOIN, LEFT JOIN, self join
clauses, and in subqueries.

IPSR Solutions Ltd www.ipsr.edu.in 8


MySql and JDBC

Joining tables using INNER JOIN


The MySQL INNER JOIN clause matches rows in one table with rows in other tables and
allows you to query rows that contain columns from both tables. The MySQL INNER JOIN
clause is an optional part of the SELECT statement. It appears immediately after the FROM
clause.
When using MySQL INNER JOIN clause, you have to specify the following criteria:

∑ First, you have to specify the main table that appears in the FROM clause.
∑ Second, you need to specify the table that you want to join with the main table, which
appears in the INNER JOIN clause. Theoretically, you can join a table with many tables.
However, for better query performance, you should limit the number of tables to join.
∑ Third, you need to specify the join condition or join predicate. The join condition appears
after the keyword ON of the INNER JOIN clause. The join condition is the rule for
matching rows between the main table and the other tables.
SELECT column_list
FROM T1
INNER JOIN T2 ON join_condition1
WHERE where_conditions;
For each row in the T1 table, the MySQL INNER JOIN clause compares it with each row of the
T2 table to check if both of them satisfy the join condition. When the join condition is matched,
it will return the row that combine columns in both T1 and T2 tables. The rows in both T1 and
T2 tables have to be matched based on the join condition. If no match found, the query will
return an empty result set. This logic is also applied if we join more than 2 tables.

If you join multiple tables that have the same column name, you have to use table qualifier to
refer to that column in the SELECT clause to avoid ambiguous column error.
For example, if both T1 and T2 tables have the same column named C in the SELECT clause,
you have to refer to the C column using the table qualifiers as T1.C or T2.C .
IPSR Solutions Ltd www.ipsr.edu.in 9
MySql and JDBC

Joining tables using LEFT JOIN


SELECT
T1.c1, T1.c2, T2.c1, T2.c2
FROM
T1 LEFT JOIN T2
ON T1.c1 = T2.c1;
When we join the T1 table to the T2 table using the LEFT JOIN clause, if a row from the left
table T1 matches a row from the right table T2 based on the join condition ( T1.c1 = T2.c1 ),
this row is included in the result set. In case the row in the left table does not match the row in
the right table, the row in the left table is also selected and combined with a “fake” row from the
right table. The fake row contains NULL values for all corresponding columns in the SELECT
clause.
In other words, the LEFT JOIN clause allows you to select rows from the both left and right
tables that are matched, plus all rows from the left table ( T1 ) even there is no match found for
them in the right table ( T2 ).
Joining tables using RIGHT JOIN
SELECT
T1.c1, T1.c2, T2.c1, T2.c2
FROM
T1 RIGHT JOIN T2
ON T1.c1 = T2.c1;
The RIGHT JOIN clause allows you to select rows from the both left and right tables that are
matched, plus all rows from the right table ( T1 ) even there is no match found for them in the
left table ( T2 ).

IPSR Solutions Ltd www.ipsr.edu.in 10


MySql and JDBC

Grouping rows into subgroups using GROUP BY clause


The GROUP BY clause, which is an optional part of the SELECT statement, groups a set of
rows into a set of summary rows by values of columns or expressions. The GROUP BY clause
returns one row for each group. In other words, it reduces the number of rows in the result set.
We often use the GROUP BY clause with aggregate functions such as SUM, AVG, MAX,
MIN, and COUNT. The aggregate function that appears in the SELECT clause provides the
information about each group.
SELECT
c1, c2,..., cn, aggregate_function(ci)
FROM
table
WHERE
where_conditions
GROUP BY c1 , c2,...,cn;
The GROUP BY clause must appear after the FROM and WHERE clauses. Following the
GROUP BY keyword is a list of comma-separated columns or expressions that you want to use
as criteria to group rows.
Filtering groups using MySQL HAVING
The MySQL HAVING clause is used in the SELECT statement to specify filter conditions for a
group of rows or aggregates.
The MySQL HAVING clause is often used with the GROUP BY clause. When using with the
GROUP BY clause, we can apply a filter condition to the columns that appear in the GROUP
BY clause. If the GROUP BY clause is omitted, the HAVING clause behaves like the WHERE
clause.
The HAVING clause applies the filter condition to each group of rows, while the WHERE
clause applies the filter condition to each individual row.

IPSR Solutions Ltd www.ipsr.edu.in 11


MySql and JDBC

Inserting data into tables using MySQL INSERT statement


The MySQL INSERT statement allows you to insert one or more rows into a table.
INSERT INTO table(column1,column2...)
VALUES (value1,value2,...);
In order to insert multiple rows into a table, you use the INSERT statement with the following
syntax:
INSERT INTO table(column1,column2...)
VALUES (value1,value2,...), (value1,value2,...), ...;
If you specify the value of the corresponding column for all columns in the table, you can
ignore the column list in the INSERT statement.
Updating data using MySQL UPDATE statement
We use the UPDATE statement to update existing data in a table. We can use the UPDATE
statement to change column values of a single row, a group of rows, or all rows in a table.
UPDATE table_name
SET
column_name1 = expr1,
column_name2 = expr2,
...
WHERE condition;
Using MySQL DELETE to Remove Data from Tables
To remove data from a single table, you use the following DELETE statement:
DELETE FROM table
[WHERE conditions]
The DELETE statement returns the number of rows deleted.

IPSR Solutions Ltd www.ipsr.edu.in 12


MySql and JDBC

JDBC – Java Database Connectivity


Java Database Connectivity in short called as JDBC. It is a java API which enables the java
programs to execute SQL statements. It is an application programming interface that defines
how a java programmer can access the database in tabular format from Java code using a set of
standard interfaces and classes written in the Java programming language. JDBC provides
methods for querying and updating the data in Relational Database Management system such as
SQL, Oracle, MySql etc.
Common JDBC Components:
The JDBC API provides the following interfaces and classes:
∑ DriverManager: This interface manages a list of database drivers and matches connection requests
from the java application with the proper database driver using communication sub protocol. The first
driver that recognizes a certain sub protocol under JDBC will be used to establish a database connection.
∑ Driver: This interface handles the communications with the database server. You will interact directly
with Driver objects very rarely. Instead, you use DriverManager object, which manages objects of this
type. It also abstracts the details associated with working with Driver objects.
∑ Connection: Interface with all methods for contacting a database. The connection object represents
communication context, i.e., all communication with database is through connection object only.
∑ Statement: You use objects created from this interface to submit the SQL statements to the database.
Some derived interfaces accept parameters in addition to executing stored procedures.
∑ PreparedStatement: Use when you plan to use the SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.
∑ ResultSet: These objects hold data retrieved from a database after you execute an SQL query using
Statement objects. It acts as an iterator to allow you to move through its data.
∑ SQLException: This class handles any errors that occur in a database application.
Creating JDBC Application:
There are following six steps involved in building a JDBC application:
1. 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.
2. Register the JDBC driver .Requires that you initialize a driver so you can open a communications channel
with the database.

IPSR Solutions Ltd www.ipsr.edu.in 13


MySql and JDBC

3. Open a connection. Requires using the DriverManager.getConnection() method to create a Connection


object, which represents a physical connection with the database.
4. Execute a query .Requires using an object of type Statement for building and submitting an SQL statement
to the database.
5. Extract data from resultset. Requires that you use the appropriate ResultSet.getXXX() method to retrieve
the data from the result set.
6. Clean up the environment .Requires explicitly closing all database resources versus relying on the JVM's
garbage collection.
Sample code

Note: while using delete, update or insert queries, use stmt.executeUpdate();


The CallableStatement Objects
Just as a Connection object creates the Statement and PreparedStatement objects, it also creates the
CallableStatement object, which would be used to execute a call to a database stored procedure.
Consider a stored procedure created in MySql.

Three types of parameters exist: IN, OUT, and INOUT.


IPSR Solutions Ltd www.ipsr.edu.in 14
MySql and JDBC

Parameter Description
IN A parameter whose value is unknown when the SQL statement is created. You bind
values to IN parameters with the setXXX() methods.

OUT A parameter whose value is supplied by the SQL statement it returns. You retrieve
values from the OUT parameters with the getXXX() methods.

INOUT A parameter that provides both input and output values. You bind variables with the
setXXX() methods and retrieve values with the getXXX() methods.

The following function

To list all procedures created on the database : Show PROCEDURE STATUS


To show the procedure definition: show CREATE PROCEDURE procedure_name

IPSR Solutions Ltd www.ipsr.edu.in 15

You might also like