0% found this document useful (0 votes)
61 views8 pages

JDBC Basics for Java Database Connection

This document provides instructions for a Java lab on using the JDBC API to connect to and interact with databases. Students will learn how to connect to Microsoft SQL Server to perform basic CRUD operations like reading, inserting, updating and deleting data. The lab objectives are explained and steps are provided to set up the JDBC driver, connect to the database, execute queries with and without parameters, and handle result sets. Finally, practical exercises are described where students will build a program to manage product data that connects using a provided URL, displays a menu of options to perform CRUD operations, and uses JDBC to execute SQL statements.

Uploaded by

vate202
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views8 pages

JDBC Basics for Java Database Connection

This document provides instructions for a Java lab on using the JDBC API to connect to and interact with databases. Students will learn how to connect to Microsoft SQL Server to perform basic CRUD operations like reading, inserting, updating and deleting data. The lab objectives are explained and steps are provided to set up the JDBC driver, connect to the database, execute queries with and without parameters, and handle result sets. Finally, practical exercises are described where students will build a program to manage product data that connects using a provided URL, displays a menu of options to perform CRUD operations, and uses JDBC to execute SQL statements.

Uploaded by

vate202
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Ton Duc Thang University

Faculty of Information Technology

JAVA TECHNOLOGY
(503111)
LAB 2

LAB OBJECTIVES
Use the Java Database Connectivity API (JDBC) - a JAVA standard library that allows connecting and
working with database systems. The Microsoft SQL Server database is used for example purposes in
this lab (other database systems can also be used in a similar way). After completing these exercises,
students will know how to use JDBC to connect and interact with mssql databases, perform basic
operations such as reading data, adding/inserting data, updating or delete data in the database.

JDBC SETUP
To use the JDBC API, we first need to download the driver corresponding to the database system we
want to use. These drivers are usually in the form of *.jar files, they can be downloaded at the
database vendor's website (Microsoft, Oracle, Mysql, etc).
• Once you have downloaded the *.jar files, you need to include them in the classpath of
your java project. There are different ways to do this, if you work with Eclipse you can
create a folder named libs, then copy the *.jar libraries into this folder and add them to
the classpath by selecting the library , right-click and choose Build Path --> Add to Build
Path (Figure 1).
• The second way to include the jdbc library to the project is to use the Maven dependency.
To do this, you need to create a java maven project (on Eclipse or Intellij Idea) then copy
the <dependency> script of the jdbc version corresponding to the database into the
[Link] file (Figure 2).

Java Technology - Week 02 – Page 1


Ton Duc Thang University
Faculty of Information Technology

Figure 1. Add *.jar files to classpath of a java project using Eclipse IDE

Figure 2. Setup mssql-jdbc dependency in a maven project with Intellij Idea tool
[Link]

Java Technology - Week 02 – Page 2


Ton Duc Thang University
Faculty of Information Technology

USING JDBC API

Steps to connect and interact with a database in JDBC


1. Create and connect to database server
2. Make queries
3. Close connection

1. Create and connect to database server

To connect to a database server in JDBC, a connection string needs to be specified. This connection
string contains important information of the server such as: hostname/ip of the server, username
and password to login to the server, the name of the database to work with and some other necessary
information.

Some examples of connection strings:

RDBMS JDBC driver name URL format

jdbc:sqlserver://hostname;user=admin;password=111111
[Link]
MS SQL ;databaseName=Lab02;encrypt=true;trustServerCertificat
ServerDriver
e=true;

MySQL [Link] jdbc:mysql://hostname/dbname?useSSL=false

ORACLE [Link] jdbc:oracle:thin:@hostname:port Number:databaseName

DB2 [Link].DB2Driver j[Link]hostname:port Number/databaseName

Sybase [Link] jdbc:sybase:Tds:hostname: port Number/databaseName

Assuming microsoft sql server is selected to make the connection, then the program to connect to
mssql server will be written similar to the following:

Java Technology - Week 02 – Page 3


Ton Duc Thang University
Faculty of Information Technology

In case of successful connection, nothing happens. If the connection fails, an exception with details
will be printed to the console.

2. Make queries

2.1 Query does not return results


Queries that do not return results can have many different cases. They are sql statements that do
not contain the select keyword. Most of these statements make some changes on the server side e.g.
adding data, deleting data or updating data.
These queries may or may not contain input parameters, such as a create table statement, a table
delete command, etc. With these statements, the Statement object is used to execute the statement
as shown below.

Execute a statement with no parameters and no results with a Statement object

Java Technology - Week 02 – Page 4


Ton Duc Thang University
Faculty of Information Technology

2.2 Check the result of the query


For sql statements accept parameters, we use PreparedStatement to execute the statement.
Inserting data into a table can be classified to statements that does not return data. However, in fact
we still need to know the status of the statement execution. More specifically, we need to know how
many lines (records) have been added/removed/updated by the last statement. This can be checked
through the result returned from the Prepared Statement object's executeUpdate() method.

Execute a statement with arguments using a Prepared Statement object. Although the statement does not return
the data of the table, we also need to know how many rows have been added/deleted/updated as a result

Java Technology - Week 02 – Page 5


Ton Duc Thang University
Faculty of Information Technology

3.3 Queries return data


For queries that return data (mostly select statements), we can use Statement or Prepared
Statement, depending on whether the statement contains parameters or not. In both cases, the
executeQuery() method needs to be called to execute the statement and get the data through the
ResultSet object.
ResultSet is an object that contains references to data lines in the result of sql statement execution.
Each time we read a stream of data by calling the .next() method.

In JDBC, the position of the parameters starts from 1

Java Technology - Week 02 – Page 6


Ton Duc Thang University
Faculty of Information Technology

PRACTICAL EXERCISES
Write a java program that uses jdbc to connect to any database system (mysql or ms sqlserver). The
program must accept the connection url from the command line arguments, you must not hardcode
the url in the source code. This connection url contains all the information to the server and the
necessary login information.

When the connection is successful, the program performs the following initial functions:

• Create a database named ProductManagement if the database doesn't already exist.


• If the Product table already exists, delete the table and then recreate it from scratch.

Next, the program displays a menu for the user to choose the functions they want to. The user enters
the number to select the function he/she want to run, the program executes that function, then
prints the results to the console (if any) and then display the original menu again until the user selects
the "exit" menu item to stop the program. The list of functions that the program supports includes:
1. Read product list
2. Read a product by input id
3. Add a new product, the result is the product id (auto increment)
4. Update a product
5. Delete a product
6. Exit

Example of menu displayed in the program


The program must be written in the following files:

Java Technology - Week 02 – Page 7


Ton Duc Thang University
Faculty of Information Technology

• [Link]: the given file, do not edit this file.


• [Link]: A POJO file that contains descriptive information for a product.
• ProductDAO: this class implements the Repository interface. You should write database
connection functions here.
• [Link]: contains the main method and use the above classes to form a complete
program.

Additional classes can be added if necessary for the exercise.

Java Technology - Week 02 – Page 8

Common questions

Powered by AI

The JDBC API enhances security primarily through the use of PreparedStatement for SQL operations requiring parameters. This approach prevents SQL injection attacks by separating SQL logic from data, ensuring that user input is treated as data rather than executable code. Furthermore, PreparedStatement compiles the SQL statement once, allowing efficient repeated execution with different parameters, safeguarding against modifications to the structure of the statement and enhancing performance .

The choice between Statement and PreparedStatement in JDBC hinges on factors such as security, efficiency, and type of query. PreparedStatement is preferable for parameterized queries, as it prevents SQL injection attacks by treating inputs strictly as data. It also enhances performance by pre-compiling SQL code and allowing it to be reused for multiple executions with different inputs. In contrast, Statement is suited for static SQL commands without input parameters. Given these considerations, PreparedStatement is often recommended for dynamic queries requiring input parameterization, ensuring both security and efficiency .

The executeUpdate() method in JDBC significantly impacts data manipulation operations by providing feedback on the execution status. It returns an integer indicating the number of rows affected by the SQL statement, allowing developers to verify the success of operations such as insertions, updates, and deletions. This feedback is essential for confirming that the operation has affected the intended data set and for handling potential errors or discrepancies in data manipulation processes .

Utilizing a Maven project setup involves creating a Maven project in the preferred IDE and defining the JDBC dependency in the pom.xml file. This process is significant as it simplifies dependency management by automatically downloading and linking all necessary library files through Maven's Project Object Model. This setup ensures that the project has the correct version of the JDBC driver and other dependencies, promoting consistency and reducing the risk of errors related to library versions. Furthermore, Maven assists in managing project builds and distributions efficiently .

In a JDBC-based Java program, each class serves specific responsibilities contributing to the overall function. The Repository.java is unmodifiable; it defines methods for database operations. Product.java acts as a Plain Old Java Object (POJO), representing database entities like 'Product'. ProductDAO implements Repository and manages database connections, handling SQL executions for CRUD operations. Program.java contains the main method and orchestrates these classes, facilitating user interaction with a menu-driven interface. This design ensures clear separation of concerns, making code maintainable and scalable .

The main steps involve downloading and including JDBC driver files in the project classpath or setting up Maven dependencies. Then, create and connect to the database server by specifying a connection string, followed by making queries and closing the connection. The connection string should include server information like hostname, username, and database name .

In JDBC, queries that return data, typically select statements, use either a Statement or PreparedStatement object. The executeQuery() method is called to execute the statement, retrieving data via a ResultSet object. For queries not returning data, such as insertions or updates, the executeUpdate() method is used to identify the number of rows affected. The PreparedStatement is preferred when SQL statements include parameters, ensuring optimized execution through parameterized queries. These different methods cater to distinct needs based on whether data returns are expected .

For SQL queries that do not return results, such as data insertion or deletion, a Statement object is used to execute the SQL command. Even though these operations do not return data, it's crucial to check the execution status, which can indicate how many rows have been affected by the operation. The JDBC API facilitates this by using the executeUpdate() method of the PreparedStatement object to determine the number of rows added, removed, or updated .

A well-formed connection string is crucial in JDBC as it contains all the necessary information for establishing a connection to the database server, including the hostname, credentials, and database name. Misconfigurations can lead to connection failures, incorrect database selections, or security vulnerabilities by exposing sensitive details. Without accurate information, the program cannot effectively communicate with the database, leading to errors and operational inefficiencies .

Designing a menu-driven Java program using JDBC would involve structuring the application into several key classes: Product.java to define the product entity; ProductDAO to handle database interactions and implement database operations such as create, read, update, and delete (CRUD); and Program.java, which would execute the main logic and handle user interactions. The menu interface, displayed via the command line, allows users to choose operations like viewing product lists or modifying entries. The design would prioritize modularity, enabling maintainability and extensibility, with each function verifying and handling user input before executing database actions .

You might also like