JAVA获取数据库连接的五种方式
package Chapter19Jdbc.JdbcConnection;
import com.mysql.jdbc.Driver;
import org.junit.jupiter.api.Test;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
/**
* Written by 3778
* 连接数据库的五种方式
*/
public class Demo {
public static void main(String[] args) {
}
@Test
public void methodOne() throws SQLException {
//注册驱动
Driver driver = new Driver();
//得到连接
String url = "jdbc:mysql://localhost:3306/db03";
//将用户名和密码放入到properties对象
Properties properties = new Properties();
//user和password是固定格式意为用户名与密码
properties.setProperty("user", "root");
properties.setProperty("password", "lyc");
//连接数据库
Connection connection = driver.connect(url, properties);
System.out.println(connection);
}
@Test
public void methodTwo() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
//通过反射加载Driver类(动态加载,更加灵活,减少依赖性)
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
//得到连接
String url = "jdbc:mysql://localhost:3306/db03";
//将用户名和密码放入到properties对象
Properties properties = new Properties();
//user和password是固定格式意为用户名与密码
properties.setProperty("user", "root");
properties.setProperty("password", "lyc");
//连接数据库
Connection connection = driver.connect(url, properties);
System.out.println(connection);
}
@Test
public void methodThree() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
//通过反射加载Driver类(动态加载,更加灵活,减少依赖性)
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
//得到连接
String url="jdbc:mysql://localhost:3306/db03";
String user="root";
String password="lyc";
//注册Driver驱动(使用DriverManage替代Driver进行统一管理,扩展性更优)
DriverManager.registerDriver(driver);
Connection connection=DriverManager.getConnection(url,user,password);
System.out.println(connection);
}
@Test
public void methodFour() throws ClassNotFoundException, SQLException { //方式3的简化版
//通过反射加载Driver类(动态加载,更加灵活,减少依赖性)
//在加载Driver类时,源码自动完成注册
Class.forName("com.mysql.jdbc.Driver"); //mysql驱动5.1.6以及更高的驱动版本可以无需调用Class.forName(),自动调用;
//得到连接
String url="jdbc:mysql://localhost:3306/db03";
String user="root";
String password="lyc";
Connection connection=DriverManager.getConnection(url,user,password);
System.out.println(connection);
}
@Test
public void methodFive() throws IOException, ClassNotFoundException, SQLException {
//在方式4的基础上改进,增加配置文件,让连接mysql更加灵活
//通过Properties对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql5_7.properties"));
//获取相关信息
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
Class.forName(driver);
Connection connection=DriverManager.getConnection(url,user,password);
System.out.println(connection);
}
}