杰瑞科技汇

Java连接数据库,Connection对象如何正确使用?

Of course! The term "connection Java" is broad, but it almost always refers to how a Java application connects to an external resource. The most common types of connections are:

Java连接数据库,Connection对象如何正确使用?-图1
(图片来源网络,侵删)
  1. Database Connections (using JDBC)
  2. Network Connections (using Sockets)
  3. HTTP Connections (making web requests)

Let's break down each one with code examples.


Database Connection (JDBC - Java Database Connectivity)

This is the most frequent meaning of "connection Java." It's the standard API for Java applications to interact with databases (like MySQL, PostgreSQL, Oracle, etc.).

Key Components:

  • Driver: A specific library for a particular database (e.g., mysql-connector-java).
  • Connection String: A URL that specifies the database location, port, and name.
  • Credentials: The username and password for the database.
  • Connection Object: Represents the active session with the database.
  • Statement / PreparedStatement: Objects used to execute SQL queries.
  • ResultSet: An object that holds the data returned from a query.

Example: Connecting to a MySQL Database

Step 1: Add the JDBC Driver You need to include the database driver in your project. If you're using Maven, add this to your pom.xml:

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.0.33</version> <!-- Use the latest version -->
</dependency>

Step 2: Write the Java Code

Java连接数据库,Connection对象如何正确使用?-图2
(图片来源网络,侵删)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseConnectionExample {
    // Database connection details
    private static final String DB_URL = "jdbc:mysql://localhost:3306/your_database";
    private static final String USER = "your_username";
    private static final String PASS = "your_password";
    public static void main(String[] args) {
        // Using try-with-resources to ensure the connection is closed automatically
        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS)) {
            System.out.println("Connection to MySQL database successful!");
            // --- Example 1: Using Statement (for simple queries) ---
            System.out.println("\n--- Using Statement ---");
            String sqlSelect = "SELECT id, name, email FROM users";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sqlSelect);
            while (rs.next()) {
                // Retrieve by column name for robustness
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String email = rs.getString("email");
                System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);
            }
            // --- Example 2: Using PreparedStatement (recommended for security and performance) ---
            System.out.println("\n--- Using PreparedStatement ---");
            String sqlInsert = "INSERT INTO users (name, email) VALUES (?, ?)";
            // The '?' are placeholders for parameters
            PreparedStatement pstmt = conn.prepareStatement(sqlInsert);
            pstmt.setString(1, "Alice"); // Set the first parameter
            pstmt.setString(2, "alice@example.com"); // Set the second parameter
            int rowsAffected = pstmt.executeUpdate();
            System.out.println(rowsAffected + " row(s) inserted.");
        } catch (SQLException e) {
            System.err.println("Connection to MySQL database failed!");
            e.printStackTrace();
        }
    }
}

Network Connection (Sockets)

This is for low-level, direct communication between two machines over a network. One application acts as a server (listens for connections) and the other as a client (initiates the connection).

Example: A Simple Echo Server and Client

Server Code (Listens for connections and echoes back messages)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServer {
    public static void main(String[] args) {
        int port = 6789;
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Server is listening on port " + port);
            // The accept() method waits until a client connects
            Socket clientSocket = serverSocket.accept();
            System.out.println("Client connected: " + clientSocket.getInetAddress());
            // Set up streams to read from and write to the client
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println("Received from client: " + inputLine);
                out.println("Server Echo: " + inputLine); // Echo back to client
            }
        } catch (IOException e) {
            System.err.println("Server exception: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Client Code (Connects to the server and sends messages)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class SimpleClient {
    public static void main(String[] args) {
        String hostname = "localhost"; // or the server's IP address
        int port = 6789;
        try (Socket socket = new Socket(hostname, port)) {
            System.out.println("Connected to the server.");
            // Set up streams
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
            String userInput;
            System.out.println("Enter messages to send to the server (type 'exit' to quit):");
            while ((userInput = stdIn.readLine()) != null) {
                if ("exit".equalsIgnoreCase(userInput)) {
                    break;
                }
                out.println(userInput); // Send message to server
                // Read the server's response
                String response = in.readLine();
                System.out.println("Server response: " + response);
            }
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + hostname);
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " + hostname);
            e.printStackTrace();
        }
    }
}

HTTP Connection (Making Web Requests)

Modern Java applications use the java.net.http package (Java 11+) or libraries like Apache HttpClient or OkHttp to make HTTP requests to web services or APIs.

Java连接数据库,Connection对象如何正确使用?-图3
(图片来源网络,侵删)

Example: Using java.net.http (Modern Approach)

This is the standard, built-in way to make HTTP requests in Java 11 and later.

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class HttpRequestExample {
    public static void main(String[] args) {
        // 1. Create an HttpClient
        HttpClient client = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_2)
                .connectTimeout(Duration.ofSeconds(10))
                .build();
        // 2. Create an HttpRequest
        HttpRequest request = HttpRequest.newBuilder()
                .GET() // or .POST, .PUT, etc.
                .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
                .header("Accept", "application/json")
                .build();
        try {
            // 3. Send the request and get the response
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            // 4. Process the response
            System.out.println("Status Code: " + response.statusCode());
            System.out.println("Response Body:");
            System.out.println(response.body());
        } catch (Exception e) {
            System.err.println("Request failed: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Summary: Which Connection to Use?

Connection Type Purpose Key Technology Best For
Database Connection Interacting with a database (CRUD operations). JDBC Any application that needs to store or retrieve persistent data.
Network Socket Direct, low-level communication between two applications. java.net.Socket Custom protocols, game servers, peer-to-peer applications.
HTTP Connection Communicating with web servers and APIs. java.net.http (or Apache HttpClient) Consuming REST APIs, web scraping, microservices communication.

When someone says "connection Java," they are most likely referring to JDBC for database connectivity, as it's a fundamental concept for most Java developers.

分享:
扫描分享到社交APP
上一篇
下一篇