方式一:
@Test public void test01() throws SQLException { // 创建一个数据库驱动器对象 Driver driver = new Driver(); // url地址 String url = "jdbc:mysql://localhost:3306/girls"; // 创建一个Properties对象,将账号和密码放进去 Properties pro = new Properties(); pro.setProperty("user", "root"); pro.setProperty("password", "root"); // 传参进行连接 Connection connect = driver.connect(url, pro); System.out.println(connect); }
方式二:
@Test public void test02() throws Exception { // 通过反射来实例化Driver对象 Class<?> aClass = Class.forName("com.mysql.jdbc.Driver"); Driver driver = (Driver) aClass.newInstance(); // url地址 String url = "jdbc:mysql://localhost:3306/girls"; // 创建一个Properties对象,将账号和密码放进去 Properties pro = new Properties(); pro.setProperty("user", "root"); pro.setProperty("password", "root"); // 传参进行连接 Connection connect = driver.connect(url, pro); System.out.println(connect); }
方式三:
@Test public void test3() throws SQLException, ClassNotFoundException { // 加载驱动 Class.forName("com.mysql.jdbc.Driver"); // 获取链接 Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/girls", "root", "root"); System.out.println(connection); }
方式四:
1.写一个配置文件,db.properties
url = jdbc:mysql://localhost:3306/girls username = root password = root classDriver = com.mysql.jdbc.Driver
@Test public void test4() throws Exception { // 读取配置文件 InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/lili/db.properties"); // 加载配置文件 Properties properties = new Properties(); properties.load(in); // 获取属性值 String url = properties.getProperty("url"); String username = properties.getProperty("username"); String classDriver = properties.getProperty("classDriver"); String password = properties.getProperty("password"); // 加载驱动 Class.forName(classDriver); // 连接 Connection connection = DriverManager.getConnection(url, username, password); System.out.println(connection); }