韩顺平 零基础30天学会Java
方式一
- 获取Driver实现类对象
// 1、创建驱动
Driver driver = new Driver();
// 2、得到连接(url,用户名和密码,driver.connect)
String url="jdbc:mysql://localhost:3306/hsp_db02";
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","123456");
Connection connect = driver.connect(url, properties);
- 缺点:直接使用 com.mysql.jdbc.Driver() 属于金改价再,灵活性差,依赖性强
方式二
- 利用反射机制,动态加载,更加灵活,减少依赖性
//使用反射,动态加载
Class cls = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) cls.newInstance();
String url="jdbc:mysql://localhost:3306/hsp_de02";
Properties properties = new Properties();
properties.setProperty("user","root");//这里写自己数据库的用户名
properties.setProperty("password","123456");//这里写自己数据库的密码
Connection connect = driver.connect(url, properties);
方式三
- 使用 DriverManager 替换Driver
//使用反射加载类,拿到一个class对象
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
//使用class对象创建一个driver对象,
Driver driver = (Driver) aClass.newInstance();
//创建url、user、password
String url="jdbc:mysql://localhost:3306/hsp_db02";
String user="root";
String password="123456";
DriverManager.registerDriver(driver);
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
方式四
- 使用Class.forName 自动完成注册驱动 – 在加载Driver类的时候,自动完成注册
- 这种方式是在开发中使用最多的
Class cls = Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/hsp_db02";
String user="root";
String password="123456";
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
方式五
- 使用配置文件,连接数据库更灵活
- 在实际开发中推荐使用
- 在 src 文件夹下新建配置文件mysql.properties,其内容如下
user=root
password=123456
url=jdbc:mysql://localhost:3306/hsp_db02
driver=com.mysql.cj.jdbc.Driver
- 连接
//通过properties 对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src/mysql.properties"));
//获取配置
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
//反射机制
Class<?> aClass = Class.forName(driver);
//获取连接
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);