Chap5.1 Databaseconnection
Chap5.1 Databaseconnection
(Part 1)
Database Connection
Outline
• Topics: JDBC to MySQL Database Access
• Introduction
• Make a connection
• Execute a SQL select statement
Database Management
Systems (DBMS)
A software that is specifically designed to store, retrieve,
and manipulate large amounts of data in an organized
and efficient manner.
4. Process the result − Retrieve the value for a specific field from a specific
record
Open a connection
The Driver Class for MySQL must be loaded from
the mysql-connector JAR file location.
https://dev.mysql.com/downloads/connector/j
/
OR
https://mvnrepository.com/artifact/mysql/my
sql-connector-java
Database Connection
Open a Connection
• Before we can access data in a database, we must
open a connection to the MySQL server.
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(URL,
login, password);
• Steps:
• Loading the driver for MySQL Server database:
• Class.forName(“com.mysql.cj.jdbc.Driver”); // depends on the
particular Driver
• Making Connection
• Connects to given JDBC URL with given user name and
password
• URL = “jdbc:mysql://host:3306/database_name”;
• Returns a connection object
Database Connection
Open a connection
Execute a query
Example:
rs.next();
int empID = rs.getInt(1);
//step 3: create the statement object
Statement stmt = conn.createStatement();
stmt.executeUpdate("INSERT into employeedb (empNo, empName,
emailAdd, mobPhoneNo) values ('UTHM001', 'zanes', 'zanes@uthm.edu.my',
'01812121212');"");
//step 4: Execute the query
ResultSet rs = stmt.executeQuery("SELECT empNo, empName, emailAdd,
mobPhoneNo from employeedb");
//use loop to fetch/retrieve all data from table
// ...
//step 5: clean-up environment
rs.close();
stmt.close();
conn.close();
ResultSet