📜  JBDC - SQL (1)

📅  最后修改于: 2023-12-03 14:43:05.209000             🧑  作者: Mango

JDBC - SQL

Introduction

JDBC stands for Java Database Connectivity. It is a Java API that provides a standard interface for connecting Java applications to databases. SQL stands for Structured Query Language, which is a programming language used for managing and manipulating relational databases. In combination, JDBC and SQL allow Java programs to access and manipulate database information.

Benefits of JDBC
  1. Portability: JDBC API is platform-independent and works on all major operating systems.

  2. Scalability: JDBC driver managers allow you to connect to different databases and switch between them as needed.

  3. Flexibility: JDBC API provides different types of JDBC drivers that can be used to access databases.

JDBC Components

There are four JDBC components:

  1. Driver Manager: Manages the loaded drivers and establishes the database connection.

  2. Driver: Provides a connection to a specific data source.

  3. Connection: Represents a connection to the database.

  4. Statement: Represents an SQL statement that is executed against the database.

SQL Commands

SQL commands are used to manage and manipulate the data in a relational database. Some of the most commonly used SQL commands are:

  1. Select: Retrieves data from the database.
SELECT column1, column2, ... FROM table_name;
  1. Insert: Adds data to the database.
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
  1. Update: Modifies data in the database.
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
  1. Delete: Removes data from the database.
DELETE FROM table_name WHERE condition;
JDBC Code Example

Here is a simple example of a Java program that demonstrates the use of JDBC and SQL to retrieve data from a database:

import java.sql.*;

public class JdbcExample {
   static final String DB_URL = "jdbc:mysql://localhost/mydatabase";
   static final String USER = "username";
   static final String PASS = "password";

   public static void main(String[] args) {
      try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
         Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT id, name, age FROM employees")) {
         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();
      }
   }
}