java,import java.sql.Connection;,import java.sql.DriverManager;,import java.sql.SQLException;,,public class MySQLConnection {, public static void main(String[] args) {, String url = "jdbc:mysql://localhost:3306/数据库名?useSSL=false&serverTimezone=UTC";, String user = "用户名";, String password = "密码";,, try {, Class.forName("com.mysql.cj.jdbc.Driver");, Connection connection = DriverManager.getConnection(url, user, password);, System.out.println("连接成功");, connection.close();, } catch (ClassNotFoundException e) {, e.printStackTrace();, } catch (SQLException e) {, e.printStackTrace();, }, },},

以下是使用Java连接MySQL数据库的详细代码,包括小标题和单元表格:

java连接mysql数据库代码java连接mysql数据库代码

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySQLConnectionDemo {
    public static void main(String[] args) {
        // 加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        // 连接数据库
        String url = "jdbc:mysql://localhost:3306/数据库名?useSSL=false&serverTimezone=UTC";
        String user = "用户名";
        String password = "密码";
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, user, password);
            System.out.println("数据库连接成功!");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        // 执行查询操作
        String query = "SELECT * FROM 表名";
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            statement = connection.createStatement();
            resultSet = statement.executeQuery(query);
            while (resultSet.next()) {
                System.out.println("字段1:" + resultSet.getString("字段1") + ",字段2:" + resultSet.getString("字段2"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

请将上述代码中的数据库名用户名密码表名字段1字段2等替换为实际的值。

java连接mysql数据库代码java连接mysql数据库代码

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。