<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.32</version>
</dependency>
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "123456";
// Class.forName("com.mysql.jdbc.Driver");
try {
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println("Connected to the database!");
// 编写sql
PreparedStatement statement = connection.prepareStatement("select * from user where id = ? ");
statement.setInt(1,1);
// 执行sql
ResultSet resultSet = statement.executeQuery();
User user=null;
// 处理数据
if (resultSet.next()){
int id = resultSet.getInt("id");
val name = resultSet.getString("name");
int age = resultSet.getInt("age");
String email = resultSet.getString("email");
user = new User(id,name,age,email);
System.out.println(user);
}
statement.close();
connection.close();
} catch (SQLException e) {
System.out.println("Failed to connect to the database!");
e.printStackTrace();
}
}
@Data
@AllArgsConstructor
class User{
int id;
String name;
int age;
String email;
}