admin管理员组

文章数量:1794759

Java连接MySQL数据库的五种方式

Java连接MySQL数据库的五种方式

声明:作品非本人原创,通过观看康师傅视频整理所得,仅供参考学习!

视频地址:尚硅谷JDBC核心技术视频教程(康师傅带你一站式搞定jdbc)_哔哩哔哩_bilibili


方式一:

@Test public void testConnection1() throws SQLException { Driver driver = new com.MySQL.cj.jdbc.Driver(); // Driver driver = new com.mysql.jdbc.Driver(); String url = "jdbc:mysql://localhost:3306/test"; //将用户名和密码封装在Properties中 Properties info = new Properties(); info.setProperty("user","root"); info.setProperty("password","123456"); Connection conn = driver.connect(url,info); System.out.println(conn); }

方式二:

//方式二:对对象一的迭代 @Test public void testConnection2() throws Exception { //1.获取Driver实现类对象:通过反射 Class clazz = Class.forName("com.mysql.cj.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); }

方式三:

@Test public void testConnection3() throws Exception{ //1.获取 Driver实现类的对象 Class clazz = Class.forName("com.mysql.cj.jdbc.Driver"); Driver driver = (Driver) clazz.newInstance(); //2、提供另外三个连接的基本信 String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "123456"; //注册驱动 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"; String user = "root"; String password = "123456"; //2.获取 Driver实现类的对象(可省略) Class.forName("com.mysql.cj.jdbc.Driver"); // Driver driver = (Driver) clazz.newInstance(); // // // //注册驱动 // DriverManager.registerDriver(driver); //获取连接 Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn); }

方式五:

//方式五(final版):将数据库连接需要的4个基本信申明在配置文件,通过读取配置文件的方式,获取连接 /* * 1.此方法的好处 * 1.1、实现了数据与代码的分离,实现了解耦。 * 1.2、如果需要修改修改配置文件信,可以避免程序重新打包。 */ @Test public void getConnection5() throws Exception { //1、读取配置文件中的4个基本信 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); System.out.println(conn); }

jdbc.properties文件:

# jdbc.properties user=root password=123456 url=jdbc:mysql://localhost:3306/test driverClass=com.mysql.cj.jdbc.Driver

本文标签: 五种方式数据库javamySQL