21xrx.com
2025-03-27 14:51:18 Thursday
文章检索 我的文章 写文章
Java如何使用JDBC连接MySQL数据库
2023-06-15 10:22:01 深夜i     --     --
Java JDBC MySQL 数据库连接 SQL语句

文章:

Java作为一种优秀的编程语言,在开发过程中经常需要与数据库进行交互。而MySQL作为广泛使用的关系型数据库之一,使用Java连接MySQL数据库也逐渐成为了开发中的常见需求。在本文中,我们将介绍Java如何通过JDBC来连接MySQL数据库。

首先,我们需要了解JDBC(Java Database Connectivity)的概念。JDBC是Java平台下与关系型数据库进行交互的重要API。通过JDBC,我们可以在Java环境下连接各种关系型数据库,包括MySQL、Oracle、SQL Server等等。

接下来我们以连接MySQL数据库为例,介绍Java连接MySQL数据库的步骤:

1. 加载MySQL JDBC 驱动程序。在使用 JDBC 连接MySQL数据库之前,需要加载与MySQL对应的JDBC驱动程序。

2. 连接MySQL 数据库。使用 DriverManager 类的 getConnection() 方法与 MySQL 数据库建立连接。

3. 执行SQL语句。通过建立的连接与MySQL数据库进行交互,可以执行各种 SQL 查询和更新语句。

代码实现:

import java.sql.*;
public class ConnectMySQL {
  public static void main(String[] args) {
    String driver = "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/test";
    String user = "root";
    String password = "root";
    Connection conn = null;
    Statement stmt = null;
    try {
      Class.forName(driver);
      conn = DriverManager.getConnection(url, user, password);
      stmt = conn.createStatement();
      String sql = "SELECT * FROM student";
      ResultSet rs = stmt.executeQuery(sql);
      while (rs.next()) {
        String name = rs.getString("name");
        int age = rs.getInt("age");
        System.out.println("Name: " + name + ", Age: " + age);
      }
      rs.close();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      try {
        if (stmt != null) stmt.close();
        if (conn != null) conn.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }
}

在上面的代码中,我们使用了 MySQL Connector/J 驱动来连接 MySQL 数据库。其中,URL需要指定数据库的 IP 地址、端口号和数据库名。

  
  

评论区