// 导入必要的包
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class MySQLJDBCDriverExample {
    // JDBC URL, 用户名和密码
    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/your_database";
    private static final String JDBC_USER = "your_username";
    private static final String JDBC_PASSWORD = "your_password";
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            // 1. 注册 JDBC 驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2. 打开连接
            System.out.println("Connecting to database...");
            connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
            // 3. 执行查询
            System.out.println("Creating statement...");
            statement = connection.createStatement();
            String sql = "SELECT id, name FROM your_table";
            resultSet = statement.executeQuery(sql);
            // 4. 处理结果集
            while (resultSet.next()) {
                // Retrieve by column name
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                // Display values
                System.out.print("ID: " + id);
                System.out.println(", Name: " + name);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 5. 关闭资源
            try {
                if (resultSet != null) resultSet.close();
                if (statement != null) statement.close();
                if (connection != null) connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}Class.forName("com.mysql.cj.jdbc.Driver") 用于加载 MySQL 的 JDBC 驱动类。这一步在较新的 JDBC 版本中是可选的,因为驱动程序会自动注册。DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD) 用于建立与数据库的连接。Statement 对象执行 SQL 查询,并通过 executeQuery 方法获取结果集。ResultSet 对象,逐行读取查询结果。ResultSet、Statement 和 Connection,以释放资源。请根据实际情况替换 your_database、your_username、your_password 和 your_table。
上一篇:mysql改密码的命令
下一篇:mysql 转大写
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站