JDBC-SQL-Java
JDBC-SQL-Java
Topic 5: Connection
● What is a Connection?
○ An object that represents a physical connection to a database.
○ It is the primary means of communication with the database.
○ All database operations (executing queries, managing transactions) are
performed through a Connection object.
● Establishing a Connection:
○ The DriverManager.getConnection() method is used to establish a connection.
○ It takes a database URL, username, and password as arguments.
○ Database URL Format: jdbc:subprotocol:subname
■ jdbc: The protocol.
■ subprotocol: The name of the JDBC driver being used (e.g., mysql,
postgresql, oracle).
■ subname: Varies depending on the driver and database, usually includes
host, port, and database name (e.g., //localhost:3306/mydatabase).
● Example Code (Establishing a Connection):
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Replace with your DB
details
String user = "myuser"; // Replace with your DB username
String password = "mypassword"; // Replace with your DB password
try (Connection connection = DriverManager.getConnection(url, user, password))
{
// Connection is successfully established here
System.out.println("Database connection successful!");
// You can now use the 'connection' object to perform database operations
} catch (SQLException e) {
System.err.println("Database connection failed!");
e.printStackTrace();
}
}
}
● Closing a Connection:
○ It is crucial to close the connection when you are finished with it to release
resources.
○ Use the close() method of the Connection object.
○ Using a try-with-resources block (as shown in the example above) is the
recommended way to ensure the connection is closed automatically, even if
errors occur.
Topic 6: Statement
● What is a Statement?
○ An object used to execute static SQL statements and return results.
○ Suitable for executing SQL queries where the SQL string is fixed and does not
change with different data.
● Creating a Statement:
○ Obtained from a Connection object using the createStatement() method:
Statement statement = connection.createStatement();
● Executing SQL Queries with Statement:
○ executeQuery(String sql): For executing SELECT queries. Returns a ResultSet.
○ executeUpdate(String sql): For executing INSERT, UPDATE, DELETE, and DDL
(Data Definition Language) statements (like CREATE TABLE, DROP TABLE).
Returns an integer representing the number of rows affected for DML
statements.
○ execute(String sql): For executing SQL statements that might return multiple
results or different types of results. Useful for stored procedures. Returns true
if the first result is a ResultSet, false if it's an update count or no result.
● Example Code (Using Statement for SELECT):
● Limitations of Statement:
○ Vulnerable to SQL injection if user input is directly concatenated into the SQL
string.
○ Performance can be lower for repeated executions of the same query with
different data, as the database has to parse and plan the query each time.
● Setting Parameters:
○ Use the setX(int parameterIndex, X value) methods, where X is the data type
(e.g., setString, setInt, setDouble). The parameterIndex starts from 1.
preparedStatement.setString(1, "Alice");
preparedStatement.setInt(2, 30);
Topic 8: ResultSet
● What is a ResultSet?
○ An object that represents the data returned by a database query, typically a
SELECT statement.
○ It acts as an iterator, providing methods to move through the rows of the
query result.
○ It holds a cursor that points to the current row. Initially, the cursor is
positioned before the first row.
● Processing a ResultSet:
○ next(): Moves the cursor to the next row. Returns true if there is a next row,
false otherwise. You typically use this in a while loop to iterate through all
rows.
○ getX(int columnIndex) or getX(String columnLabel): Retrieves the value of the
specified column in the current row, where X is the data type (e.g., getString,
getInt, getDouble, getDate). Column indexes start from 1. Using column labels
(names) is generally preferred for readability.
● Example Code (Processing a ResultSet):
● Closing a ResultSet:
○ Like Connection and Statement, ResultSet objects should be closed to release
resources.
○ Using a try-with-resources block is the best practice.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
public class JDBCExample {
// Database credentials and URL
static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
static final String USER = "myuser";
static final String PASS = "mypassword";
public static void main(String[] args) {
// Using try-with-resources for automatic resource management
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, age FROM users")) {
// Process the results
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
String sql = "INSERT INTO products (name, price) VALUES (?, ?)";
try (PreparedStatement preparedStatement = connection.prepareStatement(sql))
{
preparedStatement.setString(1, "Tablet");
preparedStatement.setDouble(2, 350.00);
int rowsAffected = preparedStatement.executeUpdate();
System.out.println(rowsAffected + " row(s) inserted.");
} catch (SQLException e) {
e.printStackTrace();
}
String sql = "SELECT id, name, price FROM products WHERE price > ?";
try (PreparedStatement preparedStatement = connection.prepareStatement(sql))
{
preparedStatement.setDouble(1, 100.00);
try (ResultSet rs = preparedStatement.executeQuery()) {
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
double price = rs.getDouble("price");
System.out.println("ID: " + id + ", Name: " + name + ", Price: " + price);
}
}
} catch (SQLException e) {
e.printStackTrace();
}