yan061

导航

Java JDBC操作数据库

  • 添加依赖
    <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;
}

posted on 2024-02-04 14:06  yan061  阅读(14)  评论(0编辑  收藏  举报