杰瑞科技汇

mac mysql java

Of course! Setting up a MySQL database and connecting it to a Java application on a Mac is a very common task. Here’s a comprehensive, step-by-step guide covering everything from installation to a complete Java example.

We'll break this down into three main parts:

  1. Installing MySQL on macOS
  2. Setting up a Java Project
  3. Writing and Running the Java Code to Connect to MySQL

Part 1: Installing MySQL on macOS

There are two popular ways to install MySQL on a Mac: using Homebrew (recommended for developers) or downloading the official DMG file.

Option A: Using Homebrew (Recommended)

Homebrew is a package manager for macOS that makes installation incredibly simple.

  1. Install Homebrew (if you don't have it): Open your Terminal (you can find it in /Applications/Utilities/ or search for it with Spotlight) and run:

    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

    Follow the on-screen instructions.

  2. Install MySQL using Homebrew: Once Homebrew is ready, run this command:

    brew install mysql
  3. Start the MySQL Server: After installation, you need to start the MySQL service. You can do this with:

    brew services start mysql

    This will start MySQL automatically whenever you start your Mac. To stop it, use brew services stop mysql.

  4. Secure the Installation: Run the security script to set a root password and remove some insecure defaults.

    mysql_secure_installation

    This interactive script will guide you through:

    • Setting a root password (remember this!).
    • Removing anonymous users.
    • Disallowing remote root login.
    • Removing test databases.
    • Reloading the privileges. It's highly recommended to answer "Y" (yes) to all of these.

Option B: Using the Official DMG File

  1. Download the Installer: Go to the official MySQL downloads page and download the "macOS" version (the DMG file).

  2. Run the Installer: Open the DMG file and follow the on-screen instructions. It will install the MySQL server, a preference pane for managing it, and a command-line tool.

  3. Start MySQL Server:

    • Go to System Settings > MySQL (or System Preferences > MySQL on older macOS versions).
    • Click the "Start MySQL Server" button.
  4. Secure the Installation: Open your Terminal and run the same command as above:

    mysql_secure_installation

Part 2: Setting up a Java Project

We'll use Maven to manage our project and its dependencies. It's the standard for most Java projects.

  1. Create a Project Directory: In your Terminal, navigate to where you want to create your project and run:

    mkdir mysql-java-project
    cd mysql-java-project
  2. Create a Maven Project Structure: Maven uses a standard directory layout. Let's create it:

    mkdir -p src/main/java
    mkdir -p src/main/resources
  3. Create the pom.xml file: This is the heart of a Maven project. It defines dependencies, plugins, and project information. Create a file named pom.xml in the mysql-java-project directory with the following content:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.example</groupId>
        <artifactId>mysql-java-project</artifactId>
        <version>1.0-SNAPSHOT</version>
        <properties>
            <maven.compiler.source>11</maven.compiler.source>
            <maven.compiler.target>11</maven.compiler.target>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>
        <dependencies>
            <!-- MySQL Connector/J is the official JDBC driver for MySQL -->
            <dependency>
                <groupId>com.mysql</groupId>
                <artifactId>mysql-connector-j</artifactId>
                <version>8.0.33</version> <!-- Use a recent version -->
            </dependency>
        </dependencies>
    </project>

Part 3: Writing and Running the Java Code

Now let's create the Java code to connect to our database.

Step 1: Create a Database and User in MySQL

First, let's create a database and a specific user for our application to use.

  1. Log in to MySQL as root: In your Terminal, run:

    mysql -u root -p

    You'll be prompted for the root password you set earlier.

  2. Run the following SQL commands:

    -- Create a new database for our project
    CREATE DATABASE my_app_db;
    -- Create a new user with privileges only on our new database
    -- Replace 'your_password' with a strong password
    CREATE USER 'java_app_user'@'localhost' IDENTIFIED BY 'your_password';
    -- Grant all privileges on our database to the new user
    GRANT ALL PRIVILEGES ON my_app_db.* TO 'java_app_user'@'localhost';
    -- Apply the changes
    FLUSH PRIVILEGES;
    -- Exit the MySQL shell
    EXIT;

Step 2: Create the Java Source File

  1. Create the Java file: Inside the src/main/java directory, create a file named DatabaseConnector.java.

    touch src/main/java/DatabaseConnector.java
  2. Write the Java code: Open DatabaseConnector.java in your favorite code editor (like VS Code, IntelliJ, or even TextEdit) and paste the following code:

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.sql.ResultSet;
    public class DatabaseConnector {
        // --- Database Connection Details ---
        // Replace with your actual database details
        private static final String DB_URL = "jdbc:mysql://localhost:3306/my_app_db";
        private static final String USER = "java_app_user";
        private static final String PASS = "your_password"; // <-- IMPORTANT: Change this!
        public static void main(String[] args) {
            // The try-with-resources statement ensures that the connection is closed automatically.
            try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS)) {
                System.out.println("Connection to MySQL database successful!");
                // --- Create a table and insert data (Example) ---
                createAndPopulateTable(conn);
                // --- Query the data (Example) ---
                queryTable(conn);
            } catch (SQLException e) {
                System.err.println("Connection failed!");
                System.err.println("Error: " + e.getMessage());
                e.printStackTrace();
            }
        }
        private static void createAndPopulateTable(Connection conn) throws SQLException {
            // Use try-with-resources for Statement to ensure it's closed
            try (Statement stmt = conn.createStatement()) {
                // Create a table if it doesn't exist
                String createTableSQL = "CREATE TABLE IF NOT EXISTS users (" +
                                        "id INT AUTO_INCREMENT PRIMARY KEY, " +
                                        "name VARCHAR(50), " +
                                        "email VARCHAR(50))";
                stmt.executeUpdate(createTableSQL);
                System.out.println("Table 'users' created or already exists.");
                // Insert some data (avoiding duplicates for demo purposes)
                String insertSQL = "INSERT IGNORE INTO users (name, email) VALUES (?, ?)";
                try (var pstmt = conn.prepareStatement(insertSQL)) {
                    pstmt.setString(1, "Alice");
                    pstmt.setString(2, "alice@example.com");
                    pstmt.executeUpdate();
                    pstmt.setString(1, "Bob");
                    pstmt.setString(2, "bob@example.com");
                    pstmt.executeUpdate();
                    System.out.println("Data inserted into 'users' table.");
                }
            }
        }
        private static void queryTable(Connection conn) throws SQLException {
            System.out.println("\n--- Querying users table ---");
            String selectSQL = "SELECT id, name, email FROM users";
            try (Statement stmt = conn.createStatement();
                 ResultSet rs = stmt.executeQuery(selectSQL)) {
                // Loop through the result set and print the data
                while (rs.next()) {
                    int id = rs.getInt("id");
                    String name = rs.getString("name");
                    String email = rs.getString("email");
                    System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);
                }
            }
        }
    }

Step 3: Compile and Run the Application

  1. Compile the code using Maven: In your terminal, make sure you are in the mysql-java-project directory and run:

    mvn compile

    This will download the MySQL JDBC driver and compile your Java code.

  2. Run the application: Now, run the compiled code:

    mvn exec:java -Dexec.mainClass="DatabaseConnector"

You should see output similar to this:

Connection to MySQL database successful!
Table 'users' created or already exists.
Data inserted into 'users' table.
--- Querying users table ---
ID: 1, Name: Alice, Email: alice@example.com
ID: 2, Name: Bob, Email: bob@example.com

Congratulations! You have successfully connected a Java application to a MySQL database on your Mac.

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