Home >Database >Mysql Tutorial >How to Connect Java to a MySQL Database?

How to Connect Java to a MySQL Database?

DDD
DDDOriginal
2024-12-19 11:05:34300browse

How to Connect Java to a MySQL Database?

Connect Java to a MySQL Database

Step-by-Step Guide

1. Install MySQL Server and JDBC Driver

  • Download the MySQL server and install it.
  • Download the MySQL JDBC driver and add it to the classpath.

2. Create MySQL Database and User

  • Create the javabase database using the following command:
    CREATE DATABASE javabase DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
  • Create a Java user and grant it access:
    `CREATE USER 'java'@'localhost' IDENTIFIED BY 'password';
    GRANT ALL ON javabase.* TO 'java'@'localhost' IDENTIFIED BY 'password';`

3. Determine JDBC URL

The JDBC URL for connecting to the MySQL database is:

jdbc:mysql://hostname:port/databasename

Set the hostname to localhost for local connections, the port to 3306 (default), and the databasename to javabase.

4. Test MySQL Connection with Java

Write the following Java code to test the connection:

String url = "jdbc:mysql://localhost:3306/javabase";
String username = "java";
String password = "password";

try (Connection connection = DriverManager.getConnection(url, username, password)) {
    System.out.println("Database connected!");
} catch (SQLException e) {
    throw new IllegalStateException("Cannot connect the database!", e);
}

Troubleshooting

  • If you face "No suitable driver found" error, make sure the JDBC driver is loaded in the classpath.
  • If you encounter connection refusal or timeout errors, verify network connectivity and MySQL server status.
  • For further troubleshooting assistance, refer to the official MySQL documentation.

The above is the detailed content of How to Connect Java to a MySQL Database?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn