1.连接数据库三种方式
//连接数据库的URL private String url = "jdbc:mysql://localhost:3306/day17"; // jdbc协议:数据库子协议:主机:端口/连接的数据库 // private String user = "root";//用户名 private String password = "root";//密码
方法一:创建驱动程序对象
//1.创建驱动程序类对象 Driver driver = new com.mysql.jdbc.Driver(); //新版本 //Driver driver = new org.gjt.mm.mysql.Driver(); //旧版本 //设置用户名和密码 Properties props = new Properties(); props.setProperty("user", user); props.setProperty("password", password); //2.连接数据库,返回连接对象 Connection conn = driver.connect(url, props);
方法二:使用驱动器类连接数据库(注册了2次没必要)
Driver driver = new com.mysql.jdbc.Driver(); //Driver driver2 = new com.oracle.jdbc.Driver(); //1.注册驱动程序(可以注册多个驱动程序) DriverManager.registerDriver(driver); //DriverManager.registerDriver(driver2); //2.连接到具体的数据库 Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn);