📅  最后修改于: 2023-12-03 15:14:14.511000             🧑  作者: Mango
In this tutorial, we will see how to connect to a MySQL database using Java. We will be using the JDBC (Java Database Connectivity) API to connect to the database.
Before proceeding, make sure you have the following:
To create a connection to the MySQL database, follow these steps:
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");
Here, mydb
is the name of the database you want to connect to, root
is the username, and password
is the password. You can replace them with your own values.
Once you have a connection to the database, you can use it to execute queries. Here's an example:
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM users");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String email = resultSet.getString("email");
System.out.printf("id: %d, name: %s, email: %s\n", id, name, email);
}
This code will select all the records from the users
table and print them to the console.
Once you're done with the connection, make sure to close it using the close()
method:
connection.close();
That's it! Now you know how to connect to a MySQL database using Java. If you have any questions or comments, feel free to leave them below.