方式一
//获取driver的实现类对象,是由数据库厂商提供的
Driver driver = new com.mysql.jdbc.Driver();
//jdbc:mysql:协议
//localhost:ip地址
//3306:默认mysql的端口号
//test:test数据库
String url = "jdbc:mysql://localhost:3306/test";
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("password", "123456");
Connection conn = driver.connect(url, info);
**方式二:**程序中不出现第三方的api,使程序有更好的可移植性
//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);
**方式三:**用DriverManager替换Driver
//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);
**方式四:**对方式三的改进,只用加载驱动,不用显式的注册驱动。
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
//加载驱动的时候,把Driver类中的静态代码块执行了,完成driver的注册(静态代码块如下截图所示)
Class.forName("com.mysql.jdbc.Driver");
//相较于方式三可以省略如下操作
// Driver driver = (Driver)clazz.newInstance();
// DriverManager.registerDriver(driver);
Connection conn = DriverManager.getConnection(url, user, password);
**方式五:**将数据库连接需要的四个基本信息声明在配置文件中,通过加载配置文件的方式,获取连接。
1、实现了数据和代码的分离,实现了解耦
2、修改代码,就要对类从新打包。如果需要修改配置文件信息,可以避免程序重新打包。
//1、读取配置文件中的四个基本信息
InputStream is = ConnectionTest.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);