连接数据库第一版-2023-02-25

public class jdbcStudy {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1.加载驱动,加载之前要把mysql-connector-java.jar包导入并加入到library中
        Class.forName("com.mysql.jdbc.Driver");

        //2.用户信息 useSSL 需要为false, 为TRUE 好像会报错
        String url = "jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8&useSSL=false";
        String username = "root";
        String password = "123456";

        //3.连接数据库
        Connection connection = DriverManager.getConnection(url,username,password);

        //4.执行sql的对象 statement  创建一个执行对象
        Statement statement = connection.createStatement();

        //5.去执行sql语句
        String sql ="SELECT * FROM account";
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()){
            System.out.println("id= "+resultSet.getObject("id"));
            System.out.println("name= "+resultSet.getObject("name"));
            System.out.println("money= "+resultSet.getObject("money"));
            System.out.println("-------------------------------");
        }

        //6.释放连接
        resultSet.close();
        statement.close();
        connection.close();

    }
}
posted @ 2023-02-25 09:21  Rui2022  阅读(13)  评论(0编辑  收藏  举报