yan061

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

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   yan061  阅读(19)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示