将Java连接数据库操作封装到MySQL类中

public class MySQL {

    final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    final String DB_URL = "jdbc:mysql://localhost:3306/student_message?serverTimezone=UTC&characterEncoding=utf-8";

    final String USER = "root";
    final String PASS = "1234";
    Connection conn = null;
    Statement stmt = null;
    
    public void account_lo(int account,int password)//账户注册,参数为两个整形
    {
        
        try{
            // 注册 JDBC 驱动
            Class.forName(JDBC_DRIVER);

            // 打开链接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL,USER,PASS);

            // 执行查询
            System.out.println(" 实例化Statement对象...");
            stmt = conn.createStatement();
            String sql;

            sql = "insert into account values("+account+","+password+")";//向数据库中插入数据
            stmt.execute(sql);
            System.out.println("save successful");
            conn.close();
        }catch(SQLException se){
            // 处理 JDBC 错误
            se.printStackTrace();
        }catch(Exception e){
            // 处理 Class.forName 错误
            e.printStackTrace();
        }finally{
            // 关闭资源
            try{
                if(stmt!=null) stmt.close();
            }catch(SQLException se2){
            }// 什么都不做
            try{
                if(conn!=null) conn.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }

   

}

该类主要实现了账户注册的方法,即增的方法。

实现删,改,查也是类似方法。

posted @ 2021-11-04 23:36  又一岁荣枯  阅读(195)  评论(0编辑  收藏  举报