Java初探 连接到Mysql数据库 - 百年刘傲天

in Java with 0 comment

Java连接数据库

首先要下载连接mysql的驱动
这里使用runoob提供的链接

在IDEA中把jar文件添加到project中
步骤如下
File->Project Structure->Modules->Dependencies->点击右侧一列的加号->Library->Java->找到你下载的jar文件,点击OK

public class DemoController {
    public String index(){
        try{
            //加载MySQL驱动
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("成功加载MySQL驱动");
        }catch (ClassNotFoundException el){
            System.out.println("找不到MySQL驱动!");
            el.printStackTrace();
        }
        //连接MySQL的地址
        String url = "jdbc:mysql://localhost:3306/demo";
        Connection conn;
        try{
            //登陆MySQL
            conn = DriverManager.getConnection(url, "root", "root");
            Statement stmt = conn.createStatement();
            System.out.println("成功连接到数据库!");

            String sql = "SELECT * FROM user";
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()){
                System.out.print("学号:");
                System.out.println(rs.getInt(1));
                System.out.print("姓名:");
                System.out.println(rs.getString(2));
            }
            rs.close();
            stmt.close();
            conn.close();
        }catch (SQLException e){
            e.printStackTrace();
        }

        return "Hello Spring Boot";
    }
}
Responses