方式一:
// 1.获取Driver对象 Driver driver = new com.mysql.jdbc.Driver(); // 2.提供要连接的数据库 String url = "jdbc:mysql://localhost:3306/test"; // 3.提供连接需要的用户名和密码 Properties info = new Properties(); info.setProperty("user", "root"); info.setProperty("password", "123456"); // 4.获取连接 Connection conn = driver.connect(url, info); System.out.println(conn);
方式二:
// 1.通过反射获取Driver对象 Class clazz = Class.forName("com.mysql.jdbc.Driver"); Driver driver = (Driver) clazz.newInstance(); // 2.提供要连接的数据库 String url = "jdbc:mysql://localhost:3306/test"; // 3.提供连接需要的用户名和密码 Properties info = new Properties(); info.setProperty("user", "root"); info.setProperty("password", "123456"); // 4.获取连接 Connection conn = driver.connect(url, info); System.out.println(conn);
方式三:
// 1.通过反射获取Driver对象 Class clazz = Class.forName("com.mysql.jdbc.Driver"); Driver driver = (Driver) clazz.newInstance(); // 2.提供连接的基本信息 String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "123456"; // 3.注册驱动 DriverManager.registerDriver(driver); // 4.获取连接 Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn);
方式四:
// 1.通过反射获取Driver对象 Class clazz = Class.forName("com.mysql.jdbc.Driver"); // 2.提供连接的基本信息 String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "123456"; // 3.获取连接 Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn);
方式五:
// 1.读取配置文件 InputStream is = Main.class.getClassLoader().getResourceAsStream("jdbc.properties"); Properties pros = new Properties(); pros.load(is); String user = pros.getProperty("user"); String password = pros.getProperty("password"); String url = pros.getProperty("url"); String driverClass = pros.getProperty("driverClass"); // 2.加载驱动 Class.forName(driverClass); // 3.获取连接 Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn);
配置文件
user=root password=123456 url=jdbc:mysql://localhost:3306/test driverClass=com.mysql.jdbc.Driver