连接数据库

释缘s 2019-12-19 11:44:14
哪位大佬会java连接sql,帮帮我
...全文
51 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_45511075 2019-12-20
  • 打赏
  • 举报
回复
我也想知道qaq
  • 打赏
  • 举报
回复

    // MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
    //static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    //static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB";

    // MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
    final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    final String DB_URL = "jdbc:mysql://localhost:3306/rgtest?useSSL=false&serverTimezone=UTC";


    // 数据库的用户名与密码,需要根据自己的设置
    static final String USER = "root";
    static final String PASS = "123456";
    Connection conn = null;
        Statement stmt = null;
        try {
            // 注册 JDBC 驱动
            Class.forName(JDBC_DRIVER);

            // 打开链接
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            // 执行查询
            stmt = conn.createStatement();
            String sql;
            if (true) {
                sql = "SELECT * FROM information_module_conf ";
                ResultSet rs = stmt.executeQuery(sql);
                // 展开结果集数据库
                while (rs.next()) {
                    // 通过字段检索
                   
                    Map<String,String> map = new HashMap<>();
                    String id= rs.getString("id");
                   
                    // 输出数据

                    map.put("id:" , id);
                    
                    System.out.println(map.toString());

                }
                //获取一共多少条数据
                rs.last();
                System.out.println(rs.getRow());

                // 完成后关闭
                rs.close();
            } else {
                sql = "UPDATE goods_inf SET commission_amount = '5' WHERE id='14'";
                int retCode = stmt.executeUpdate(sql);
                System.out.println(retCode);
            }
            stmt.close();
            conn.close();
        } catch (SQLException ex) {
            // 处理 JDBC 错误
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
            ex.printStackTrace();
        } catch (Exception e) {
            // 处理 Class.forName 错误
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException ex) {

            }// 什么都不做
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }

58,454

社区成员

发帖
与我相关
我的任务
社区描述
Java Eclipse
社区管理员
  • Eclipse
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧