🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
What is JDBC?
Java Database Connectivity (JDBC) is an API that enables Java applications to interact with databases. It provides methods to query and update data in a database, as well as to retrieve metadata about the database itself.
SQL Server Database
SQL Server is a relational database management system developed by Microsoft. It is widely used for storing, managing, and retrieving data in various applications.
Table of Contents
- Setting Up the SQL Server Database
- Adding SQL Server JDBC Driver to Your Project
- Establishing a Database Connection
- Executing SQL Queries
- Retrieving Data
- Closing the Connection
- Conclusion
1. Setting Up the SQL Server Database
First, create a database named jdbc_example and a products table within it. Use SQL Server Management Studio or any SQL Server client to execute the following commands:
CREATE DATABASE jdbc_example;
USE jdbc_example;
CREATE TABLE products (
id INT IDENTITY(1,1) PRIMARY KEY,
name VARCHAR(100),
description VARCHAR(255),
price DECIMAL(10, 2)
);
INSERT INTO products (name, description, price) VALUES
('Laptop', 'Dell Inspiron', 75000.00),
('Smartphone', 'Samsung Galaxy', 30000.00),
('Tablet', 'Apple iPad', 50000.00);
2. Adding SQL Server JDBC Driver to Your Project
To interact with a SQL Server database, you need to add the SQL Server JDBC driver to your project. If you are using Maven, add the following dependency to your pom.xml file:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>9.4.0.jre8</version>
</dependency>
3. Establishing a Database Connection
We will start by establishing a connection to the SQL Server database using JDBC.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCExample {
private static final String URL = "jdbc:sqlserver://localhost:1433;databaseName=jdbc_example";
private static final String USER = "your_username";
private static final String PASSWORD = "your_password";
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASSWORD);
}
public static void main(String[] args) {
try (Connection connection = getConnection()) {
if (connection != null) {
System.out.println("Connected to the SQL Server database!");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
4. Executing SQL Queries
We can use the Connection interface to create a Statement object and execute SQL queries. Here, we will insert a record into the products table.
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class InsertProductExample {
public static void main(String[] args) {
String insertSQL = "INSERT INTO products (name, description, price) VALUES ('Smartwatch', 'Apple Watch Series 6', 40000.00)";
try (Connection connection = JDBCExample.getConnection();
Statement statement = connection.createStatement()) {
int rowsInserted = statement.executeUpdate(insertSQL);
System.out.println(rowsInserted + " row(s) inserted!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
5. Retrieving Data
We can use the Connection interface to create a Statement object and execute a query to retrieve data from the products table.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SelectProductExample {
public static void main(String[] args) {
String selectSQL = "SELECT * FROM products";
try (Connection connection = JDBCExample.getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(selectSQL)) {
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String description = resultSet.getString("description");
double price = resultSet.getDouble("price");
System.out.println("ID: " + id + ", Name: " + name + ", Description: " + description + ", Price: " + price);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
6. Closing the Connection
Using the try-with-resources statement ensures that the connection is closed automatically. This is important to free up database resources.
import java.sql.Connection;
import java.sql.SQLException;
public class CloseConnectionExample {
public static void main(String[] args) {
try (Connection connection = JDBCExample.getConnection()) {
if (connection != null) {
System.out.println("Connected to the SQL Server database!");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Conclusion
In this tutorial, we have covered the basics of using the JDBC Connection interface to interact with a SQL Server database. We demonstrated how to establish a connection, execute SQL queries, retrieve data, and close the connection using the try-with-resources statement. This guide should help you get started with JDBC and understand how to use the Connection interface effectively with SQL Server.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment