项目案例模板之jdbc两种连接方式

项目案例模板之jdbc两种连接方式

第一种连接方式

JDBCUtils.java

 package jdbc;
 ​
         import org.junit.jupiter.api.Test;
 ​
         import java.sql.Connection;
         import java.sql.DriverManager;
         import java.sql.SQLException;
 ​
 public class JDBCUtils {
     public static Connection connection;
     private static String url="jdbc:mysql://localhost:3306/aaa?useUnicode=true&characterEncoding=utf-8";
     private static String username="root";
     private static String password="root";
 ​
     static{
         try {
             Class.forName("com.mysql.jdbc.Driver");
             connection = DriverManager.getConnection(url,username,password);
 ​
         } catch (ClassNotFoundException e) {
             e.printStackTrace();
         } catch (SQLException e) {
             e.printStackTrace();
         }
     }
 ​
     public static Connection getConnection(){
         return connection;
     }
 ​
     @Test
     public void test(){
         Connection connection = JDBCUtils.getConnection();
         System.out.println(connection);
     }
 }

  项目案例模板之jdbc两种连接方式_第1张图片

第二种连接方式

项目案例模板之jdbc两种连接方式_第2张图片

db.properties

 url=jdbc:mysql://localhost:3306/aaa?useUnicode=true&characterEncoding=utf-8
 username=root
 password=root

JDBCUtils2.java

package jdbc;
 ​
 import org.junit.jupiter.api.Test;
 ​
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.SQLException;
 import java.util.Properties;
 ​
 public class JDBCUtils2 {
     private static Connection connection;
     private static String url;
     private static String username;
     private static String password;
 ​
     static {
         try {
             //动态加载驱动
             Class.forName("com.mysql.jdbc.Driver");
             //加载配置文件
             Properties properties = new Properties();
             properties.load(new FileInputStream("src/main/java/db.properties"));
             url = properties.getProperty("url");
             username = properties.getProperty("username");
             password = properties.getProperty("password");
 ​
             connection = DriverManager.getConnection(url,username,password);
 ​
 ​
         } catch (ClassNotFoundException e) {
             e.printStackTrace();
         } catch (FileNotFoundException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         } catch (SQLException e) {
             e.printStackTrace();
         }
     }
 ​
     public static Connection getConnection(){
         return connection;
     }
 ​
     @Test
     public void test(){
         Connection connection = JDBCUtils2.getConnection();
         System.out.println(connection);
     }
 }

  

 

 

 

 

你可能感兴趣的:(项目案例模板之jdbc两种连接方式)