public class ConnectionTest { //数据库连接方式一 @Test public void testConnection1() throws SQLException{ //获取Driver实现类的对象 Driver driver=new com.mysql.jdbc.Driver(); //jdbc:mysql:协议 //localhost:ip地址 //3306:默认MySQL的端口号 //test:数据库名 String url="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useConfigs=maxPerformance"; //将用户名密码封装在Properties Properties info=new Properties(); info.setProperty("user", "root"); info.setProperty("password", "123456789"); //获取链接 Connection conn=driver.connect(url,info); System.out.println("方法一:数据库连接成功"+conn); } //数据库连接方式二:在如下程序中不出现第三方的api,使得程序更具有可以执行,是对方式一的迭代 @Test public void testConnection2() throws Exception{ //1、获取Driver实现类的对象 ,使用反射实现 Class clazz=Class.forName("com.mysql.jdbc.Driver"); Driver driver=(Driver)clazz.newInstance();//newInstance()方法调用成功的前提,Driver有空参构造器,有权限 //2、提供要连接的数据库 String url="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useConfigs=maxPerformance"; //3、提供连接需要的用户名和密码 Properties info=new Properties(); info.setProperty("user","root"); info.setProperty("password", "123456789"); //4、获取连接 Connection conn=driver.connect(url,info); System.out.println("方法二:数据库连接成功"+conn); } //数据库连接方式三:使用DriverManager替换Driver @Test public void testConnection3() throws Exception{ //1、获取Driver实现类的对象 ,使用反射实现 Class clazz=Class.forName("com.mysql.jdbc.Driver"); Driver driver=(Driver)clazz.newInstance();//newInstance()方法调用成功的前提,Driver有空参构造器,有权限 //2、提供另外三个连接的基本信息 String url="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useConfigs=maxPerformance"; String user="root"; String password="123456789"; //注册驱动 DriverManager.registerDriver(driver); //获取连接 Connection conn=DriverManager.getConnection(url,user,password); System.out.println("方法三:数据库连接成功"+conn); } //数据库连接方式四:只需加载驱动,不用显示注册驱动 @Test public void testConnection4() throws Exception{ //1、提供另外三个连接的基本信息 String url="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useConfigs=maxPerformance"; String user="root"; String password="123456789"; //2、获取Driver实现类的对象 ,使用反射实现,mysql自动注册驱动 Class.forName("com.mysql.jdbc.Driver"); //注册驱动 //DriverManager.registerDriver(driver); //获取连接 Connection conn=DriverManager.getConnection(url,user,password); System.out.println("方法四:数据库连接成功"+conn); } //数据库连接方式五:将数据库连接需要的4个基本信息声明在配置文件中,通过读取配置文件的方式,获取连接 @Test public void testConnection5() throws Exception{ //1、读取配置文件中的信息 InputStream is=ConnectionTest.class.getClassLoader().getResourceAsStream("properties"); Properties pros=new Properties(); pros.load(is); String user=pros.getProperty("user"); String password=pros.getProperty("password"); String url=pros.getProperty("url"); String driver=pros.getProperty("driverClass"); //2、加载驱动 Class.forName(driver); //3、获取连接 Connection conn=DriverManager.getConnection(url,user,password); System.out.println("方法五:数据库连接成功"+conn); } }
第五种连接方式配置文件中的信息 如下
user=root
password=123456789
url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useConfigs=maxPerformance
driverClass=com.mysql.jdbc.Driver
将该文件存放在src目录下即可。