Lecture No 11
Lecture No 11
JAVA DATABASE
CONNECTIVITY
LECTURE OBJECTIVE
JDBC Fundamentals
JDBC Connections
JDBC Statements
1 • Connection
3 • Execute SQL\Quries
4 • Viewing\Ouput
JDBC ARCHITECTURE
JDBC ARCHITECTURE
• JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server. Essentially, a JDBC driver makes it possible to do three things:
1. Establish a connection with a data source.
2. Send queries and update statements to the data source.
3. Process the results.
• Add import statements to Java program to import required classes in your Java code.
REGISTER JDBC DRIVER
• This step causes the JVM to load the desired driver implementation into memory so that it can
fulfill your JDBC requests.
• The most common approach to register a driver is to use Java’s forName()method to
dynamically load the driver’s class file into memory, which automatically registers it. This
method is preferable because it allows to make the driver registration configurable and
portable.
• Refer the below code.
1try {
2Class.forName(“com.mysql.jdbc.Driver");
3}
4catch(ClassNotFoundException ex) {
5System.out.println("Error: unable to load driver class!");
6System.exit(1);
7}
OPENING A CONNECTION
• This is to create a properly formatted address that points to the database to which need to
connect.
• DriverManager.getConnection() requires the complete address of the database
– Database URL
– UserName
– Password
• A table lists down the popular JDBC driver names and database URL.
EXECUTING A QUERY
CLOSE
• At the end of your JDBC program, we have to close all the database connections to end each
database session. However, if you forget, Java’s garbage collector will close the connection
when it cleans up stale objects.
1 conn.close();