📜  conexion一个mysql java(1)

📅  最后修改于: 2023-12-03 15:14:14.511000             🧑  作者: Mango

Conexion with MySQL using Java

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.

Prerequisites

Before proceeding, make sure you have the following:

  • MySQL server installed and running on your machine.
  • MySQL Connector/J JAR file. You can download it from the official website.
Creating a Connection

To create a connection to the MySQL database, follow these steps:

  1. Load the MySQL Connector/J JDBC driver:
Class.forName("com.mysql.cj.jdbc.Driver");
  1. Open a connection to the database using the DriverManager class:
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.

Executing Queries

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.

Closing the Connection

Once you're done with the connection, make sure to close it using the close() method:

connection.close();
Conclusion

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.