1. Install MySQL Server and JDBC Driver
2. Create MySQL Database and User
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
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!